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
Kinetic: a page to make motion graphics in your brand, with presets, timing and versions
Adarsh63ac68293fc7
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex a93bb948..c6ba2c43 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -145,7 +145,7 @@ Every adapter implements `isConfigured`, `prepareFile`, `submit` and `poll`, and- **Round 5 part 1 (fixes-5): reachability shared with Ollama.** The busy-vs-down rules above moved to `src/server/providers/reach.ts` (`hostPort`, `takesConnection`, `ask`, `checkReach`, `sharedCheck`, `reachSync`), which Ollama's check now uses too (see LLM provider). `REACH` is exported from there, and one map of running checks (`globalThis.__fuobeReachChecks`) replaces `__fuobeComfyProbe`; `probeComfy` and `probeComfySync` keep their behaviour (`tests/comfy-reach.test.ts`).- **Round 5 part 2: soundtrack splits and asked sizes.** On `separate-soundtrack-dbs`, `prepareWorkflow()` binds `separationModel` to the model asked for, else the host's pick (`dbsModelFor` in `src/lib/av/split.ts`: DBS-TIGER on a CUDA device, DBS-BSRNN on a CPU, the other one when the pick isn't on disk). The device comes from `/system_stats` (`comfyDevice`, kept a minute) and the models on disk from `GET /models/dbs`, which ComfyUI-DBS registers (`comfyDbsModels`, read fresh at submit; callers that arrive while either request is on its way share it); a model that isn't there is refused in words, never sent. `channels` is mono or each channel (`dbsChannelsFor`), and a source with more than 2 channels (the header's count, else `params.extra.sourceChannels`) is split in mono with a mono Music & effects (`dbsSurroundBed`), because ComfyUI saves at most 2 channels. A canvas the request names (`params.extra.width` / `height`: a layout's, Soul's exact sizes) is fitted to the graph's grid and maximum side with its shape kept (`fitCanvas` in `src/lib/comfy.ts`), as the cloud's `sizeValue` fits it, so both engines render one size. Upload headers carry the channel count (`MediaInfo.channels`: WAV, FLAC, MP3 and an MP4 / MOV's first sound track in `src/lib/media-probe.ts`; WebM / Matroska in `src/server/webm-probe.ts`). The manifest's outputs gain the stems `music` and `effects` and the role `report` (a node's own account of the run).- **llm** — text steps in this process (below).-- **local** — results made in the browser (Color grading's PNG / WebM, Ads Studio composites, Kinetic Motion clips; `/api/generations/local` records them, an account's Kinetic Motion clip as its own run, with or without its own GPU or key).+- **local** — results made in the browser (Color grading's PNG / WebM, Ads Studio composites, Kinetic Motion clips, frames, contact sheets and versions; `/api/generations/local` records them, an account's Kinetic Motion clip as its own run, with or without its own GPU or key).- **mock** — demo outputs for every operation (SVG art, bundled sample clips, a tone, layers with meta, cue lists, two stems, a GLB with a turntable from `scripts/gen-demo-3d.mjs`), so the product works with zero setup. Round-4 operations answer too: a scene-3d job gets the GLB plus a grey depth PNG on the open engine and a Spectral-coloured depth PNG on the cloud, and an EXR job a sample clip with a zip that holds only a README. An extract-frames job returns as many frames as `max_frames` asks (4 without a count), so a per-frame Mixed Media demo fans out like the real one. Splat and rig jobs get the demo GLB too (`meta.format` `glb`), so a demo run never shows the splat card. Since round 4 part 5 a `video-swap` on Character Swap Studio's segment graph also returns a `master`, so a demo continuation runs like a real one. Since round 5 part 1 a `face-mosaic` job returns a demo picture with no masks. Since round 5 part 2 a `separate-audio` job on `separate-soundtrack-dbs` returns four stems (voice, music, effects and background, voice first). A request with `demo: true` (a skill's free dry run) goes to this provider whatever Settings → Demo mode says (see Pipelines).## Structured outputs@@ -380,7 +380,7 @@ Each studio keeps its data and pure planner in `src/lib/`, its server module in| studio | pure logic | server | routes | UI ||---|---|---|---|---|| **Cinema Studio** (`/cinema`, `/cinema/[id]`) | `catalog/cinema.ts`: research data (genres, eras, 33 camera moves, 50 palettes, 7 lighting presets, Emotion Wheel, 17 Soul Cast fields, grids), `compileDirector` (prose; the native Cinema Studio 4.0 fields are no longer used; since round 4 part 5 `directorFieldWords` writes a stored Cinema Studio 4.0 request's fields as those words), `planCinema` (steps with `after`, notes, blocker, cost), `takesClips` (feature-detected from the FieldMap). Round 4 part 4 (Fuobe Cinema, see Fuobe Originals): the menus per mode and engine (`CINEMA_MODELS`, the Original first, `ORIGINAL_LINES`), `CINEMA_CAMERA_LORA`, `cinemaMoveRoute`, `CAST_MODELS` / `LOCATION_MODELS`, `planLocationView`, `editPrompt`; no Higgsfield model or key check (`HIGGSFIELD_ONLY` is gone). 3D scenes (round 4): the `scene` and `recompose` actions with `SCENE_MODELS` (cloud `marigold-depth`, open `oss-scene-moge`) and `RECOMPOSE_MODELS` (cloud Nano Banana Pro or Qwen Multiple Angles, open `oss-qwen-edit` with the Multiple-Angles LoRA); `src/lib/scene3d.ts` (lens 18–300 mm and field of view, fly controls, Spectral depth decoding → point cloud, `scenePose`, `recomposePrompt`, capture size). Round 5 part 2: the `path` action (N7-5, Fly path: `planPath` films the scene's still along the path on `PATH_MODELS`, cloud `minimax-h3-max-camera` for 3–15 s, open `oss-uni3c-path` for 81 frames at 16 fps from the browser's render; priced with stand-ins while the path isn't ready, then blocked; `pathTake`) on `src/lib/camera-path.ts`, the `turnaround` action (N7-6: `planTurnaroundTake` runs `planTurnaround` as a take), and `withPlaceholders` puts a slot with `at` in its place | `cinema.ts` (projects, nested scenes, `cinema_items` with per-take meta: take, tiles, cost, req, removed; spend in SQL; the automatic cover skips depth maps), `cinema-generate.ts` (`generateInProject`: previews every step, checks the cost cap; a recompose take keeps its `camera`), `cinema-director.ts` (AI Director via `llmText`, offline fallback, never generates), `cinema-schemas.ts` (a recompose `capture`: an `/api/files/` URL, lens, aperture, pose; since round 4 part 4 the `source` take's facts: `modelId`, `prompt`, `seconds`, `resolution`, `aspectRatio`; since round 5 part 2 a path's keys, length, render and move, and a turnaround, `TurnaroundSchema` without the engine and consent); since round 5 part 2 `generateInProject` keeps a filmed path on its take (`CinemaTakeInfo.path`: the keys, the clip's real length and the move); `cinemaContext()` is `{cloudAllowed, civitai, has}` | `/api/cinema/projects[/id[/folders[/folderId] \| /items[/genId/retry \| /tiles] \| /generate \| /director]]` (generate takes `action` `scene` and `recompose`, and since round 5 part 2 `path` and `turnaround`; the project's `context` is `{cloudAllowed, civitai}`) | `components/cinema/*`: workspace (since round 4 part 4 a Share button in the header and a share item in the project menu), folder sidebar, feed (finishes Fuobe Soul stills), prompt bar (the Original first with its badge and per-engine line, models switched off left out), Director's Panel, camera moves (a route badge per move on both engines), palette editor (`color-math.ts`), grid crops (`grid-math.ts`), Soul builders (Fuobe Soul looks), autosave; `scene-actions.tsx` (Create 3D scene, priced, asks first), `scene-viewer.tsx` + `scene-engine.ts` (full-screen three.js viewer, loaded only when a scene opens; Capture uploads the framed view and queues a recompose take); since round 5 part 2 Fly path: `scene-path.tsx` (the keyframe chips with + Keyframe and Preview, the moves, length, quality, motion words and Film this path), `scene-engine.ts`'s `recordPath` (the scene rendered along the path, 81 frames at 16 fps, as VP8 WebM with exact frame times through WebCodecs and `muxWebM` in `src/lib/webm.ts`, else MediaRecorder; the open engine's guide) and `playPath` (Preview), and Turnaround video on Soul Cast results (`CastTurnaround` in `soul-builders.tsx`) |-| **Canvas** (`/canvas`, `/canvas/[id]`) | `catalog/canvas.ts`: node types and typed ports, `connectionError`, `topoOrder`, `describeNode` (a GenerationRequest validated with `planGeneration` on placeholders), `planCanvas` (run vs reuse by signature, pins), `convertEngine`, the templates (cloud and open); since round 4 part 5 `withCurrentModels` (on every board read: `toCanvas` in `src/server/canvas.ts`) and `cleanGraph` move a node on a retired model, or on a partner model's lost operation, to what replaced it (`currentNode`; an Original node keeps the cloud unless it names an engine); input ports for the round-4 operations, and a chained route fed by another node (a keyframe film, the open text-to-3D route) is refused before Run. Round 4 part 3: 18 node types (new: Change voice, Clone voice with a `voice` port type, Translate for text or video, Video concatenator with per-clip `clips` cuts, mutes and `order`, Table with `columns` and `rows`; their default models are in `PREFERRED`: `voice-change` ElevenLabs Voice Changer or `oss-chatterbox-vc`, `dub` ElevenLabs Dubbing, `translate` `text-llm` or `oss-text-llm`), 7 templates (new: `clips-film`, `table-film`; the talking avatar's sample is a Clone voice node), `concatRequest` and `rowRequest` (a node made in steps, a node run per table row: see Pipelines), `tablesFeeding`, `CONCAT_LIMITS` (50 clips, 30 fps, 512 MB a clip, cloud joins of 24), `CONCAT_RATIOS` (8 shapes, 720 on the short side) and `TABLE_LIMITS` (8 columns, 50 rows). `catalog/canvas-board.ts`: pages (`readPages`: a row saved before pages reads as page 1; `copyPage` with `remapNodeData`), groups (`groupMembers`: a node belongs to every group its top-left corner sits in; `groupTargets` for Run group), comment pins with replies, shapes and pen strokes (`penShape`, at most 400 points), `BOARD_LIMITS` (20 pages). Round 5 part 1 (O13): 10 Effects 2.0 chains as templates in their own section (`EFFECT_CHAINS`, `effectChainTemplate`, `CanvasTemplate.group`: Agamemnon, Fallen Angel, Pearl Earring…), each Your photo → "Set the scene" edit (`qwen-image-edit-2511-cloud` or `oss-qwen-edit`) → a 5 s Fuobe DoP clip with the effect's own catalog words (`effectWords`) → output, on both engines; a Canvas node can't carry a DoP preset, so a chain doesn't use an effect's LoRA, and an effect renamed in the catalog makes the module throw on import (`tests/effect-chains.test.ts` would catch it) | `canvas.ts`: zod graph (since round 4 part 3 with groups, comments and shapes, and `PagesSchema`), CRUD, `canvasView`, `runCanvas` (one generation per step with `dependsOn`, or one `createPipeline` for a node made in steps or rows; runs kept in `runs_json`), `graphProblem`, `pagesProblem`. Round 4 part 3: `graph_json` holds `{pages: [{id, name, graph}]}` (no migration; a canvas switches when next saved); `updateCanvas` takes every page or one page's graph, and a page it can't take (a 21st, or one the run names that is gone) is a `CanvasConflict` (409); a run saves every page first and runs one page, a selection or a group; the cloud concatenator's silent WAVs are written per run (`silenceWriter`), and a stored clip over 512 MB is refused (`oversizedClip`) | `/api/canvases[/id[/duplicate \| /run]]`. Since round 4 part 3 create, PATCH and run take `pages` (PATCH also `graph` with `page`; run also `page` and `group`), and responses return `pages`, not `graph` (summaries add `pageCount`) | `components/canvas/*` on @xyflow/react: editor store (`canvas-context.tsx`, `useSyncExternalStore`, `DescribeCache`, whose key follows a concatenator's tables), nodes, palette, phone node list. Round 4 part 3: `board.tsx` (groups, comments and shapes as React Flow nodes), `toolbar.tsx` (V, H, D, E, N, ⇧T, R, T, C), page tabs and per-page undo in `canvas-editor.tsx`, and in `nodes.tsx` the Clone voice, Table, concatenator and open dub hand-off (a Translate video node on an open-only install starts a `/api/dub` session, keeps it as `dubId` and offers the dubbed clip back as a Video input); phones get a page picker over the read-only board |+| **Canvas** (`/canvas`, `/canvas/[id]`) | `catalog/canvas.ts`: node types and typed ports, `connectionError`, `topoOrder`, `describeNode` (a GenerationRequest validated with `planGeneration` on placeholders), `planCanvas` (run vs reuse by signature, pins), `convertEngine`, the templates (cloud and open); since round 4 part 5 `withCurrentModels` (on every board read: `toCanvas` in `src/server/canvas.ts`) and `cleanGraph` move a node on a retired model, or on a partner model's lost operation, to what replaced it (`currentNode`; an Original node keeps the cloud unless it names an engine); input ports for the round-4 operations, and a chained route fed by another node (a keyframe film, the open text-to-3D route) is refused before Run. Round 4 part 3: 18 node types (new: Change voice, Clone voice with a `voice` port type, Translate for text or video, Video concatenator with per-clip `clips` cuts, mutes and `order`, Table with `columns` and `rows`; their default models are in `PREFERRED`: `voice-change` ElevenLabs Voice Changer or `oss-chatterbox-vc`, `dub` ElevenLabs Dubbing, `translate` `text-llm` or `oss-text-llm`), 7 templates (new: `clips-film`, `table-film`; the talking avatar's sample is a Clone voice node), `concatRequest` and `rowRequest` (a node made in steps, a node run per table row: see Pipelines), `tablesFeeding`, `CONCAT_LIMITS` (50 clips, 30 fps, 512 MB a clip, cloud joins of 24), `CONCAT_RATIOS` (8 shapes, 720 on the short side) and `TABLE_LIMITS` (8 columns, 50 rows). `catalog/canvas-board.ts`: pages (`readPages`: a row saved before pages reads as page 1; `copyPage` with `remapNodeData`), groups (`groupMembers`: a node belongs to every group its top-left corner sits in; `groupTargets` for Run group), comment pins with replies, shapes and pen strokes (`penShape`, at most 400 points), `BOARD_LIMITS` (20 pages). Round 5 part 1 (O13): 10 Effects 2.0 chains as templates in their own section (`EFFECT_CHAINS`, `effectChainTemplate`, `CanvasTemplate.group`: Agamemnon, Fallen Angel, Pearl Earring…), each Your photo → "Set the scene" edit (`qwen-image-edit-2511-cloud` or `oss-qwen-edit`) → a 5 s Fuobe DoP clip with the effect's own catalog words (`effectWords`) → output, on both engines; a Canvas node can't carry a DoP preset, so a chain doesn't use an effect's LoRA, and an effect renamed in the catalog makes the module throw on import (`tests/effect-chains.test.ts` would catch it) | `canvas.ts`: zod graph (since round 4 part 3 with groups, comments and shapes, and `PagesSchema`), CRUD, `canvasView`, `runCanvas` (one generation per step with `dependsOn`, or one `createPipeline` for a node made in steps or rows; runs kept in `runs_json`), `graphProblem`, `pagesProblem`. Round 4 part 3: `graph_json` holds `{pages: [{id, name, graph}]}` (no migration; a canvas switches when next saved); `updateCanvas` takes every page or one page's graph, and a page it can't take (a 21st, or one the run names that is gone) is a `CanvasConflict` (409); a run saves every page first and runs one page, a selection or a group; the cloud concatenator's silent WAVs are written per run (`silenceWriter`), and a stored clip over 512 MB is refused (`oversizedClip`) | `/api/canvases[/id[/duplicate \| /run \| /runs/[node]]]` (`PUT …/runs/[node]`: a Kinetic node's run, rendered in the owner's browser, kept on the board; owner only, ids the owner's finished `local-motion` results). Since round 4 part 3 create, PATCH and run take `pages` (PATCH also `graph` with `page`; run also `page` and `group`), and responses return `pages`, not `graph` (summaries add `pageCount`) | `components/canvas/*` on @xyflow/react: editor store (`canvas-context.tsx`, `useSyncExternalStore`, `DescribeCache`, whose key follows a concatenator's tables), nodes, palette, phone node list. Round 4 part 3: `board.tsx` (groups, comments and shapes as React Flow nodes), `toolbar.tsx` (V, H, D, E, N, ⇧T, R, T, C), page tabs and per-page undo in `canvas-editor.tsx`, and in `nodes.tsx` the Clone voice, Table, concatenator and open dub hand-off (a Translate video node on an open-only install starts a `/api/dub` session, keeps it as `dubId` and offers the dubbed clip back as a Video input); phones get a page picker over the read-only board || **Layers** (`/layers`, `/layers/[id]`) | `lib/layers.ts`: LayerDoc / LayerNode geometry, export scale, zip naming `layer-z{z}-{slug}.png`, stored zip, Copy JSON, `historyReducer` (same-key edits within 1.2 s are one undo), `layersModelFor`, `MAX_NODES = 200`, `MAX_REVISIONS = 50`, `TOOL_MODELS` (each tool's models per engine). Round 4 part 2: Inpaint (`inpaintPrompt`) and the Enhancer (`ENHANCE_LOOKS` Skin, Soft glow, Sharpen and Detail; `ENHANCE_DETAIL_SCALE` makes Detail 2× on every engine), text rows placed from OCR boxes (`placeTextBlocks`), `seeThrough`, `readableBackdrop`, `elementDraft`; `src/lib/ocr.ts` reads an OCR model's answer into lines with 0–1 boxes | `layers.ts`: projects and versions (autosave into the head, 409 from a stale tab), tool jobs built by `jobSteps` (a cut-out step after edits on transparent layers), "decomposed" derived from applied jobs. Round 4 part 2: `text-detect` picks op `ocr` or `text-layers` from the model's routes (cloud Ideogram 3.0 Text Layers or Florence-2 OCR, open OvisOCR3); `inpaint` sends the painted mask (and a red-tinted sketch), and `applySketch` gives mask models the mask and edit models the tinted copy (cloud Nano Banana Pro, FLUX.1 Fill [pro], Z-Image Turbo Inpaint; open FLUX.1 Fill [dev]); `enhance` is an edit with a fixed instruction (Nano Banana Pro, Seedream 5.0 Pro; open Qwen-Image-Edit 2511) or, for Detail, an upscaler (Topaz, SeedVR; open SeedVR2 or ESRGAN) | `/api/layers[/id[/versions \| /jobs[/jobId]]]` (jobs take `inpaint` with `mask` and `sketch`, and `enhance` with `settings.look`), `/api/layers/renders` (PNG-only "derived" assets) | `components/layers/*`: results measured in the browser (`measure.ts`) and laid out by `applyMeasured` (`apply.ts`), zips and composites rendered with canvas (`render.ts`), WebGL grade; paint mode on the stage (`stage.tsx`), Keep transparency on only for layers with see-through pixels (`keep-alpha.ts`), and Save as element (`save-element.tsx`: the layer's trimmed PNG through `POST /api/elements`, as a character, prop or style) || **Shorts Studio** (`/shorts`, `/shorts/[id]`) | `catalog/shorts.ts`: 44 presets, `planCloudSegments` (equal ≤10 s), `planOpenSegments` (4n+1 frames ≤81 at 16 fps), `planTake`, `planStitch`, `planShorts` (with `keepShape` for Genjutsu's restyle: no crop, framing as filmed), `chainState`; `catalog/shorts-models.ts` (what each restyle model takes, read from its v2v routes; since round 5 part 1 per engine, with "… at 30 fps" in Fuobe Shorts' price line); `lib/trim-range.ts`. Since round 5 part 1 the default is Fuobe Shorts on both engines (`SHORTS_ORIGINAL`; `planOriginalTake`, `originalSegmentProblem`, `originalBilledSeconds`, `vaceDownsample`: see Fuobe Originals), with Gemini Omni Flash, Kling O3 4K Edit, Happy Horse, Lucy Edit Pro, Runway Aleph 2, LTX 2.3 restyle and Wan 2.7 as cloud choices | `shorts.ts` (sessions, segments with takes and the primary take, stitches; `probeSource` reads MP4 then WebM via `webm-probe.ts`; since round 5 part 1 sessions keep `source.fps`, and a cloud Fuobe Shorts take records its `still` step), `shorts-schemas.ts` (`once(scope, requestId, fn)`: one paid submit per click, 10 min) | `/api/shorts/{probe,estimate,sessions[/id[/segments/i[/primary] \| /stitch]],presets[/id]}` | `components/shorts/*`, the shared `components/studio/video-trimmer.tsx` || **Mixed Media** (`/mixed-media`) | `catalog/mixed-media.ts`: 33 presets with settings, frames = floor(s × fps), open render (one job, on `oss-mixed-media` until round 5 part 1), cloud Fast plan (trim → restyle → original sound), preview plan. Round 4 part 2: the cloud Per frame plan (`planMixedFrames`, the cloud default until round 5 part 1): cut → `extract-frames` (every Nth frame of the clip, `frameSampling`; up to 500 a call) → one Nano Banana 2 or Seedream 5.0 Flash edit per frame (`frameEditParams`: a fixed seed on Nano Banana 2, while Seedream 5.0 Flash takes none; `planMixedFrames` gives each frame the one styled before it as a second picture, in lanes of 12 that start from the approved preview) → `images-to-video` in clips of up to 200 frames → `join-clips` at up to 2048 px (`frameJoinSize`; 4K frames are then drawn at 2K, `frameResolution`) → the cut's own sound; the limits are `FRAME_LIMITS`. Since round 5 part 1 (O9) the default on both engines is Fuobe Mixed Media (`MIXED_ORIGINAL`, `MIXED_FRAME_MODELS`: the Original first, then Nano Banana 2 and Seedream 5.0 Flash in the cloud), drawn frame by frame with no lanes (`originalFrameRequest`, `originalFrameParams`, `originalFrameSize`); `MIXED_MODES` adds Smooth on both engines (`planMixedSmooth`), and Fast stays cloud only (see Fuobe Originals) | `mixed-media.ts`: estimate (adds `mode`, `perFrameUsd`, the sampled `fps`, `providers`, `modelId`), render, preview; `cloudMode` takes `mode` or reads it from the model (a model of the other mode is a 422); since round 5 part 1 `mode: "smooth"`, `source.width` / `height` for the frame size, the look LoRAs a run can reach (civitai key, LoRA folder) with notes, and Smooth's 17-frame / 5 fps refusal before anything is paid for; `retryMixed` redoes only failed or canceled steps and what follows them (`createPipeline` `existing`, `unfilledRequest`) and cancels the old waiting ones; `framesProgress` names the frame that failed; no table (History is the feed: features `mixed-media`, `mixed-media-step`, `mixed-media-frame-step`, `mixed-media-preview`) | `/api/mixed-media[/preview \| /estimate \| /retry \| /progress?id=]` | `components/mixed-media/*` (the Restyle switch, Per frame or Fast, since round 5 part 1 also Smooth, and the price per frame) |@@ -406,6 +406,8 @@ Each studio keeps its data and pure planner in `src/lib/`, its server module inMotion graphics drawn by code, in the brand's own fonts and colours, with the words exactly as typed. A **scene** is a pure function of a **recipe** (JSON: scene, seed, size, fps, length, the typed fields, the brand, the person's own files, control values, export settings) and an absolute time: `scene.plan(input)` lays the text out once (`layout.ts`: balanced lines, never cut, never re-cased, never split mid-word; a field that doesn't fit is reported as `overflow` and blocks the render) and builds a timeline of cues (`tween.ts`, on the named curves in `ease.ts`: Bézier, closed-form springs), and `plan.evaluate(t)` gives a display list (`display.ts`: groups with transforms, clips, masks and blends; rects, ellipses, paths with stroke trim, text runs, images) in design units (1080 on the short side, `sizes.ts`). Randomness is a hash of the seed and a key (`random.ts`); there is no clock, DOM or `Math.random` in `src/lib/motion`, so any frame can be seeked in any order (`tests/motion-scenes.test.ts`). `camera2d.ts` is a 2.5D camera with parallax by depth. The browser half: `draw.ts` (`drawDisplayList`, the only code that draws a list, and SVG logo outlines read with the browser's SVG engine), `fonts.ts` (an export waits for the brand font or stops), `player.tsx` (the live preview: absolute time on animation frames, pauses off screen or in a hidden tab, rest frame for reduced motion, a smaller backing store on slow devices), `render.ts` (`renderClip`: frame i at i / fps, motion blur from shutter samples never across a cut, as many per frame as its fastest edge needs (`listTravel` in `display.ts`: one for a frame that barely moves, up to 48), WebCodecs H.264 MP4 from the canvas itself, else VP8 WebM, else the recorder) and `save.ts` (`saveMotionResult`: `POST /api/uploads` sent with `x-fuobe-kinetic: 1`, which any account may send for an MP4 or WebM clip or a PNG poster, within its space and upload limits, since no model makes them; then `POST /api/generations/local` with model `local-motion`, op `motion` and the recipe in `params.extra.motion`; nothing is downloaded from the page). Phase 1 ships the end card's five styles (`scenes/end-card/`: Draw-on, Rise, Iris, Split, Glint), whose rest frame is the still card's own layout (`planEndCard` and `renderEndCard` use the same `endCardRest` and drawer). The rest layout sizes type from the frame's short side, keeps a tall card's bottom fifth clear, and sets the words and pill in the kit colour that reads best on the brand colour (`cardColours`). Each style opens a few frames into its motion (`lead`), is readable by about 0.9 s of a 2.5 s card (`settled`), then a slow push-in (`CAMERA_FROM`, the `drift` curve) comes home on the last frame (`rest`, the poster); `signature` is the frame the style chooser shows. A saved clip carries its poster in `output.meta.poster`. Click to Ad joins the rendered card after the ad: in the cloud with its silent track and `merge-videos`, on the open engine with `oss-join-sound1`, which re-encodes the ad at 25 fps (the still card's `oss-append-endcard` copies the ad's picture instead); the open path has not yet been run end to end on a GPU.+**The Kinetic page (`/kinetic`, `src/app/(studio)/kinetic/page.tsx`, `src/components/kinetic/*`).** A static page whose studio runs in the browser (the address names a `scene`, an end card's `style`, or `from=<result>` to remix a saved one). `src/lib/motion/kinetic-catalog.ts` is the bundled scene list (the ten code templates, their slugs, which take a clip, and their motion groups from `kinetic-groups.ts`: every event of every scene in exactly one named group); `edit.ts` holds the editor's pure parts (shot windows, motion groups retimed by a monotone warp and a rate held inside their shot, the camera's clock, parameter tracks, the extra camera that always comes home on the last frame, presets worked out from the values, never stored); `finish.ts` the grade and seeded grain; `video-layer.ts` the person's own clip under the words (five scenes). The recipe gains optional `motion`, `finish`, `camera`, `look`, `groups`, `tracks`, `layers.video`, 60 fps and `export.quality` (`v` stays 1; a recipe without them draws exactly as before, `tests/motion-identity.test.ts`). The two scene wrappers (`marketingScene`, `endCardScene`) apply them, so no scene file changes. Saves: a clip (`kinetic`), a frame, a 9-frame contact sheet and versions (`kinetic-frame`, `kinetic-sheet`, `kinetic-version`, PNG pictures) through `save.ts`; undo and redo last the visit, a draft stays in the browser. `/api/generations/local` records each Kinetic result with its pixel size (a picture's own header must match its recipe). The Canvas "Kinetic" node (`components/canvas/kinetic-node.tsx`) renders in the owner's tab once per Table row and feeds Output nodes: it waits for the upstream nodes its run started, renders one node at a time per tab, skips a row that fails, keeps what it made even when stopped, and reuses a row by what it was made from.+**Marketing templates drawn by code.** Ten Marketing Studio templates are Kinetic Motion scenes instead of model prompts (`render: "code"` in `catalog/marketing.ts`, with their `scene`, typed `fields` and `easy` choices): Kinetic Headline, Line-Art Reveal, Logo Sting, Feature Cards, Dashboard Zoom, Retro Starburst, and the new Offer Badge, Big Number, Five-Star Quote and Logo End Card (the five end-card styles as its Style choice). The scenes are in `src/lib/motion/scenes/marketing/` (`kit.ts`: the light, dark and brand-colour looks from the kit with every word at 4.5:1 or more, the safe area, the pace, the tabular rolling counter, `*stars*` that mark a highlighted word and are never drawn); `outline.ts` traces a cut-out picture's edge from its transparency (marching squares, then Ramer–Douglas–Peucker) for Line-Art Reveal, and a photo without one gets a traced frame. `template.ts` turns what the template's panel holds (words, choices, size, length 5–15 s, brand, picture) into the recipe; `showcase.ts` holds the fictional brands each template opens with. The panel (`components/marketing/kinetic-template.tsx` with `components/motion/{fields,easy-chips,brand-row,made-strip}.tsx`) replaces the composer for these templates: anyone can type and play, Save renders in the tab and records the clip as `feature: "marketing-kinetic"` through `save.ts` (the same upload rule as any file; a guest gets the sign-up card and an account with neither its own GPU nor a key the Connect card before anything renders), and "Made with this template" lists the saved clips, which open in the result viewer. Their covers are rendered by the engine itself: `scripts/kinetic/render-covers.mjs` plays each showcase on the development-only page `/dev/kinetic-covers` and writes cover masters (`meta.json` `rest`: `"end"`, or the seconds of the moment the words are all set), then `pnpm eval:covers --templates` versions them into `public/previews/templates/marketing/`.## ComfyUI workflow library (`workflows/comfyui/`, `scripts/comfy/`)diff --git a/docs/public-signup.md b/docs/public-signup.mdindex 487e5717..3c2d5c2a 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -36,7 +36,11 @@ and 403 `own-gpu-tool` for a tool an account's own GPU or key doesn't run (ShortMarketing…). The pages of those tools say so up front and turn off their upload and Generate.What is drawn in the browser itself is open to try: Click to Ad's animated end card and MarketingStudio's code-drawn templates (Kinetic Motion) take a guest's words and play live (a code-drawn-template shows no "isn't available" note, as nothing is generated); their Save opens the sign-up card before anything renders. Price+template shows no "isn't available" note, as nothing is generated); their Save opens the sign-up card before anything renders.+The Kinetic page (`/kinetic`) is open the same way: a guest plays and edits every scene (Easy and Pro, presets,+timing, undo), and Save, Save frame, Save contact sheet, Save version, "Pick a clip" and an upload open the sign-up+card before anything renders or uploads. A guest's versions list is empty and `/kinetic?from=<id>` opens the scene+picker. Pricechecks (the estimate routes, and `?preview=1` on the run routes that support it) stay open, so thestudios can show prices. A guest may send 120 price checks a minute (per visitor behind a trustedreverse proxy; see below), and so may each account. A price check reads only the header of a file@@ -74,6 +78,9 @@ An account is signed in, but it sees the owner's studio as a guest does:So does Split soundtrack's **Export mix** (`POST /api/audio-tools/export`), which saves into theowner's Library, with or without a GPU. Accounts have their own uploads and runs (below), but noprojects yet.+ A Canvas Kinetic node renders in the owner's browser; keeping its run on the board+ (`PUT /api/canvases/<id>/runs/<node>`) is a canvas change like any other (403 `library` for an account, 401+ for a guest), and it takes only the owner's own finished Kinetic Motion results.Canvas shows its ready boards to guests and accounts as read-only pages (`/canvas/start/<id>`):what goes in, the steps and what comes out. Only the owner makes boards. Assist, Cinema Studio,Storyboard, Elements, Faceless Studio, Content Factory, Explainer, Ads Studio, Click to Ad and@@ -99,13 +106,16 @@ An account is signed in, but it sees the owner's studio as a guest does:- **Its own uploads are its own.** Only the account that uploaded a file can use it in a run, andno other account can open it. See [Uploads](#uploads).- **Results made in the browser (Kinetic Motion) are its own runs too.** A motion clip rendered in- the page (an animated end card, a text template) is saved with an upload and+ the page (an animated end card, a text template, anything made on the Kinetic page) is saved with an upload and`POST /api/generations/local` (`op: "motion"`, model `local-motion`). No model makes it, so anyaccount may save one, with or without its own GPU or key (the upload is sent with`x-fuobe-kinetic: 1`; see [Uploads](#uploads)). It counts as the account's own runs and files: the clip and every file it- names (its pictures, and the recipe's logo, product and pictures) must be the account's own (403- otherwise), a clip is never made from a video (400), the stored file must be the MP4 or WebM it- claims to be (400), and it shares the account's hourly run budget (60 an hour with its other runs,+ names (its pictures, and the recipe's logo, product, pictures and clip) must be the account's own (403+ otherwise). Frames, contact sheets and versions are Kinetic results too (`feature` `kinetic-frame`,+ `kinetic-sheet` or `kinetic-version`, a PNG picture of the size its recipe makes: the export size for a frame or a+ sheet, the rest frame 540 px on its long side for a version; 400 otherwise); a clip under the words must be the account's own stored video,+ and a video input is taken only when it is the recipe's own clip (`layers.video.src`; 400 otherwise). The stored+ file must be the MP4, WebM or (for those three) PNG it claims to be (400), and it shares the account's hourly run budget (60 an hour with its other runs,429). The words drawn on the clip (the recipe's fields and brand name) and its title go through thestudio's checks when they are on, whatever the page sends as the prompt, and are what the run keeps(a refusal answers 422; a result the checks want to see waits for them). It shows in the account'sdiff --git a/public/previews/templates/marketing/ms-kinetic-headline.jpg b/public/previews/templates/marketing/ms-kinetic-headline.jpgindex effc042f..6c473728 100644Binary files a/public/previews/templates/marketing/ms-kinetic-headline.jpg and b/public/previews/templates/marketing/ms-kinetic-headline.jpg differdiff --git a/public/previews/templates/marketing/ms-kinetic-headline.mp4 b/public/previews/templates/marketing/ms-kinetic-headline.mp4index bbca2933..2013d30b 100644Binary files a/public/previews/templates/marketing/ms-kinetic-headline.mp4 and b/public/previews/templates/marketing/ms-kinetic-headline.mp4 differdiff --git a/public/previews/templates/marketing/thumbs/ms-kinetic-headline.jpg b/public/previews/templates/marketing/thumbs/ms-kinetic-headline.jpgindex 89ababfb..622f55e7 100644Binary files a/public/previews/templates/marketing/thumbs/ms-kinetic-headline.jpg and b/public/previews/templates/marketing/thumbs/ms-kinetic-headline.jpg differdiff --git a/src/app/(studio)/kinetic/loading.tsx b/src/app/(studio)/kinetic/loading.tsxnew file mode 100644index 00000000..6a8d96e2--- /dev/null+++ b/src/app/(studio)/kinetic/loading.tsx@@ -0,0 +1,6 @@+import { ScenePickerShell } from "@/components/kinetic/scene-picker";++/** On the way in from a menu, Kinetic's opening screen itself stands in while the page loads. */+export default function Loading() {+ return <ScenePickerShell />;+}diff --git a/src/app/(studio)/kinetic/page.tsx b/src/app/(studio)/kinetic/page.tsxnew file mode 100644index 00000000..ae12c42c--- /dev/null+++ b/src/app/(studio)/kinetic/page.tsx@@ -0,0 +1,19 @@+import type { Metadata } from "next";+import { Suspense } from "react";+import { KineticStudio } from "@/components/kinetic/kinetic-studio";+import { ScenePickerShell } from "@/components/kinetic/scene-picker";++export const metadata: Metadata = { title: "Fuobe Kinetic Motion" };++/**+ * Fuobe Kinetic Motion: motion graphics in your brand, drawn live in the browser. The page itself is static: it sends+ * the opening screen (its title, the examples and every scene), and the studio reads its address (scene, style, from)+ * on the client, inside a Suspense boundary.+ */+export default function Page() {+ return (+ <Suspense fallback={<ScenePickerShell />}>+ <KineticStudio />+ </Suspense>+ );+}diff --git a/src/app/api/canvases/[id]/runs/[node]/route.ts b/src/app/api/canvases/[id]/runs/[node]/route.tsnew file mode 100644index 00000000..c04239cf--- /dev/null+++ b/src/app/api/canvases/[id]/runs/[node]/route.ts@@ -0,0 +1,35 @@+import { z } from "zod";+import { KINETIC_RUN_ROWS, KineticRunProblem, recordKineticRun } from "@/server/canvas";++const Id = z.string().min(1).max(40);+const Body = z+ .object({+ sig: z.string().max(400),+ ids: z.array(Id).min(1).max(KINETIC_RUN_ROWS),+ rows: z.array(Id).max(KINETIC_RUN_ROWS).optional(),+ rowSigs: z.array(z.string().max(400)).max(KINETIC_RUN_ROWS).optional(),+ })+ .superRefine((b, ctx) => {+ // One result per row, each once; the rows and their signatures line up with the results.+ if (new Set(b.ids).size !== b.ids.length) ctx.addIssue({ code: "custom", path: ["ids"], message: "A result twice" });+ if (b.rows && (b.rows.length !== b.ids.length || b.rows.some((r) => !b.ids.includes(r)))) ctx.addIssue({ code: "custom", path: ["rows"], message: "The rows" });+ if (b.rowSigs && b.rowSigs.length !== b.ids.length) ctx.addIssue({ code: "custom", path: ["rowSigs"], message: "The row signatures" });+ });++/**+ * Keeps a Kinetic node's run on the canvas: it renders in the owner's browser (each row saved as a Kinetic Motion+ * result), and this records which results it made, so the Output nodes it feeds show them. Canvas changes are the+ * owner's (the proxy refuses accounts and guests).+ */+export async function PUT(request: Request, ctx: RouteContext<"/api/canvases/[id]/runs/[node]">) {+ const { id, node } = await ctx.params;+ const parsed = Body.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Send the run's results" }, { status: 400 });+ try {+ const canvas = recordKineticRun(id, node, parsed.data);+ return Response.json({ runs: canvas.runs });+ } catch (e) {+ if (e instanceof KineticRunProblem) return Response.json({ error: e.message }, { status: e.status });+ throw e;+ }+}diff --git a/src/app/api/generations/local/route.ts b/src/app/api/generations/local/route.tsindex 42e92a4e..490eb913 100644--- a/src/app/api/generations/local/route.ts+++ b/src/app/api/generations/local/route.ts@@ -1,6 +1,9 @@+import fs from "node:fs";import { z } from "zod";+import { imageSize } from "@/lib/image-size";import { LIBRARY_MESSAGE } from "@/lib/guest-access";-import { RECIPE_MAX_BYTES, RecipeSchema } from "@/lib/motion/recipe";+import { RECIPE_MAX_BYTES, RecipeSchema, type Recipe } from "@/lib/motion/recipe";+import { designSize, exportSize } from "@/lib/motion/sizes";import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, diskHasRoom } from "@/server/account-files";import { fileAccount } from "@/server/account-library";import { accountInputProblem } from "@/server/account-inputs";@@ -10,9 +13,42 @@ import { moderateRun } from "@/server/hosted-run";import { holdForCheck } from "@/server/output-checks";import { hit, unhit } from "@/server/rate";import { db } from "@/server/db";-import { contentTypeFor, filesRel } from "@/server/storage";+import { absolutePath, contentTypeFor, filesRel } from "@/server/storage";import { runAsTenant } from "@/server/tenant";+/** Kinetic's picture results: a frame, a contact sheet, a version (PNG images; every other Kinetic result is a clip). */+const KINETIC_IMAGE_FEATURES: readonly string[] = ["kinetic-frame", "kinetic-sheet", "kinetic-version"];+const imageFeature = (f: string) => KINETIC_IMAGE_FEATURES.includes(f);++/**+ * The pixel size a Kinetic result of this recipe has: a clip, a frame and a contact sheet are the export size (even+ * sides), a version is the rest frame with 540 px on its long side (render.ts makes them the same way).+ */+function kineticOutputSize(recipe: Recipe, feature: string): { width: number; height: number } {+ if (feature === "kinetic-version") {+ const d = designSize(recipe.size);+ const k = 540 / Math.max(d.w, d.h);+ return { width: Math.max(2, Math.round(d.w * k)), height: Math.max(2, Math.round(d.h * k)) };+ }+ const { w, h } = exportSize(recipe.size);+ return { width: w - (w % 2), height: h - (h % 2) };+}++/** A stored picture's pixel size, from its first bytes (null when it can't be read). */+function storedImageSize(rel: string): { width: number; height: number } | null {+ let fd: number | null = null;+ try {+ fd = fs.openSync(absolutePath(rel), "r");+ const head = new Uint8Array(64);+ const n = fs.readSync(fd, head, 0, head.length, 0);+ return imageSize(head.subarray(0, n));+ } catch {+ return null;+ } finally {+ if (fd !== null) fs.closeSync(fd);+ }+}+const Body = z.object({feature: z.string().min(1).max(80),@@ -38,9 +74,15 @@ const Body = zif (!recipe || typeof recipe !== "object" || Array.isArray(recipe)) ctx.addIssue({ code: "custom", path: ["params", "extra", "motion"], message: "The recipe" });else if (JSON.stringify(recipe).length > RECIPE_MAX_BYTES) ctx.addIssue({ code: "custom", path: ["params", "extra", "motion"], message: "The recipe is too big" });else if (!RecipeSchema.safeParse(recipe).success) ctx.addIssue({ code: "custom", path: ["params", "extra", "motion"], message: "The recipe" });- if (b.output.kind !== "video" || !/^video\/(mp4|webm)$/.test(b.output.contentType ?? "")) ctx.addIssue({ code: "custom", path: ["output"], message: "An MP4 or WebM clip" });- // A clip is made from pictures (its logo, its product): never from a video.- if (b.inputs.video) ctx.addIssue({ code: "custom", path: ["inputs", "video"], message: "No video" });+ // A frame, a contact sheet or a version is a PNG picture; everything else is an MP4 or WebM clip.+ if (imageFeature(b.feature)) {+ if (b.output.kind !== "image" || b.output.contentType !== "image/png") ctx.addIssue({ code: "custom", path: ["output"], message: "A PNG picture" });+ } else if (b.output.kind !== "video" || !/^video\/(mp4|webm)$/.test(b.output.contentType ?? "")) ctx.addIssue({ code: "custom", path: ["output"], message: "An MP4 or WebM clip" });+ // A clip under the words is the recipe's own clip, named as its video input; nothing else is a video input.+ if (b.inputs.video) {+ const parsed = RecipeSchema.safeParse(recipe);+ if (!parsed.success || parsed.data.layers?.video?.src !== b.inputs.video) ctx.addIssue({ code: "custom", path: ["inputs", "video"], message: "The recipe's clip" });+ }}});@@ -60,7 +102,7 @@ function typeProblem(rel: string, output: { kind: string; contentType?: string }const stored = contentTypeFor(rel);if (!stored.startsWith(`${output.kind}/`)) return true;if (output.contentType && output.contentType.split(";")[0].trim().toLowerCase() !== stored) return true;- return op === "motion" && !/^video\/(mp4|webm)$/.test(stored);+ return op === "motion" && !(output.kind === "image" ? stored === "image/png" : /^video\/(mp4|webm)$/.test(stored));}/** The files a motion recipe names: its logo when it is stored here, its product and its pictures. */@@ -77,6 +119,8 @@ function recipeFiles(extra: Record<string, unknown> | undefined): Record<string,if (r.data.media?.product && stored(r.data.media.product)) out._product = r.data.media.product;const media = (r.data.media?.images ?? []).filter(stored);if (media.length) out._media = media;+ // The clip under the words (Kinetic's video layer): always a stored file.+ if (r.data.layers?.video?.src) out._clip = r.data.layers.video.src;return out;}@@ -104,6 +148,20 @@ export async function POST(request: Request) {if (typeProblem(rel, body.output, body.op)) return refuse(400, "Invalid result");const poster = body.output.meta?.poster;if (poster && (body.output.kind !== "video" || !contentTypeFor(filesRel(poster) ?? "").startsWith("image/"))) return refuse(400, "Invalid result");+ // A Kinetic result is the size its recipe makes (a picture's own header must say so), and is recorded with it; the clip+ // under its words is a stored video.+ let output: typeof body.output & { width?: number; height?: number } = body.output;+ if (body.op === "motion") {+ const recipe = RecipeSchema.parse(body.params?.extra?.motion);+ const size = kineticOutputSize(recipe, body.feature);+ if (imageFeature(body.feature)) {+ const real = storedImageSize(rel);+ if (!real || real.width !== size.width || real.height !== size.height) return refuse(400, "Invalid result");+ }+ const clip = recipe.layers?.video?.src;+ if (clip && !contentTypeFor(filesRel(clip) ?? "").startsWith("video/")) return refuse(400, "Invalid result");+ output = { ...body.output, ...size };+ }if (viewer.kind === "owner") {// The owner's own files only: never an account's file recorded as the owner's result.@@ -114,7 +172,7 @@ export async function POST(request: Request) {if (r === null || typeof fileAccount(r) === "string") return refuse(403, NOT_FOUND);}try {- return Response.json(recordLocalGeneration(body), { status: 201 });+ return Response.json(recordLocalGeneration({ ...body, output }), { status: 201 });} catch (e) {return refuse(422, (e as Error).message);}@@ -142,11 +200,11 @@ export async function POST(request: Request) {return refuse(422, checked.refusal.body.error, { code: checked.refusal.body.code });}try {- const g = runAsTenant({ kind: "account", id: account.id }, () => recordLocalGeneration({ ...body, prompt }));+ const g = runAsTenant({ kind: "account", id: account.id }, () => recordLocalGeneration({ ...body, output, prompt }));if (checked.checkOutputs) {// Held until the output check answers, as any account run's files are.const assetId = assetIdOf(body.output.url);- holdForCheck(g.id, [{ ...body.output, ...(assetId && { assetId }) }]);+ holdForCheck(g.id, [{ ...output, ...(assetId && { assetId }) }]);return Response.json(getGeneration(g.id) ?? g, { status: 201 });}return Response.json(g, { status: 201 });diff --git a/src/app/globals.css b/src/app/globals.cssindex 4f34b2dc..cf66f8fa 100644--- a/src/app/globals.css+++ b/src/app/globals.css@@ -721,3 +721,64 @@ html {@media (prefers-reduced-motion: reduce) {[data-slot="dropdown-menu-content"], [data-slot="dropdown-menu-sub-content"], [data-slot="popover-content"] { animation: none !important; }}++/*+ * Kinetic's sliders: a themed track with the value filled in the brand colour (--fill, set by the slider) and a 20 px+ * thumb, the same in light and dark (the native track is light grey on white in every theme).+ */+.k-range {+ -webkit-appearance: none;+ appearance: none;+ background: transparent;+ --fill: 0%;+ --track: color-mix(in oklab, var(--foreground) 14%, transparent);+}+.k-range::-webkit-slider-runnable-track {+ height: 6px;+ border-radius: 9999px;+ background: linear-gradient(to right, var(--primary) var(--fill), var(--track) var(--fill));+}+.k-range[dir="rtl"]::-webkit-slider-runnable-track {+ background: linear-gradient(to left, var(--primary) var(--fill), var(--track) var(--fill));+}+.k-range::-moz-range-track {+ height: 6px;+ border-radius: 9999px;+ background: var(--track);+}+.k-range::-moz-range-progress {+ height: 6px;+ border-radius: 9999px;+ background: var(--primary);+}+.k-range::-webkit-slider-thumb {+ -webkit-appearance: none;+ appearance: none;+ width: 20px;+ height: 20px;+ margin-top: -7px;+ border-radius: 9999px;+ background: var(--background);+ border: 2px solid var(--primary);+ box-shadow: 0 1px 3px rgb(0 0 0 / 0.25);+}+.k-range::-moz-range-thumb {+ width: 16px;+ height: 16px;+ border-radius: 9999px;+ background: var(--background);+ border: 2px solid var(--primary);+ box-shadow: 0 1px 3px rgb(0 0 0 / 0.25);+}+.k-range:focus-visible {+ outline: none;+}+.k-range:focus-visible::-webkit-slider-thumb {+ box-shadow: 0 0 0 4px color-mix(in oklab, var(--ring) 45%, transparent);+}+.k-range:focus-visible::-moz-range-thumb {+ box-shadow: 0 0 0 4px color-mix(in oklab, var(--ring) 45%, transparent);+}+.k-range:disabled {+ cursor: default;+}diff --git a/src/components/canvas/canvas-context.tsx b/src/components/canvas/canvas-context.tsxindex 29d1177d..8736b016 100644--- a/src/components/canvas/canvas-context.tsx+++ b/src/components/canvas/canvas-context.tsx@@ -210,6 +210,13 @@ export function buildViews(const reused = new Set(plan.reused.map((r) => r.nodeId));const out = new Map<string, NodeView>();for (const n of graph.nodes) {+ // A Kinetic node renders in the browser: its view is what feeds it and what it made (no op, no estimate).+ if (n.type === "kinetic") {+ const next: NodeView = { ...EMPTY_VIEW, counts: counts.get(n.id) ?? EMPTY_VIEW.counts, results: results.get(n.id) ?? EMPTY_RESULTS };+ const old = prev?.get(n.id);+ out.set(n.id, old && sameView(old, next) ? old : next);+ continue;+ }if (!isGenerator(n)) continue;const d = describe(n.id);const next: NodeView = {diff --git a/src/components/canvas/canvas-editor.tsx b/src/components/canvas/canvas-editor.tsxindex e6bfc2be..67cf71c5 100644--- a/src/components/canvas/canvas-editor.tsx+++ b/src/components/canvas/canvas-editor.tsx@@ -117,6 +117,7 @@ import { AddMenu, DRAG_TYPE, Palette, PaletteToggle } from "./palette";import { BoardToolbar, PAGE_PANEL_ID, PageTabs, pageTabId, TOOL_KEYS, type DragShape, type PageOps, type Tool } from "./toolbar";import { saveCanvas, useCanvasView, useRunCanvas, type CanvasView } from "./use-canvas";import { useSkillBuilder } from "@/components/skills/skill-builder-provider";+import { KINETIC_RUN_EVENT } from "./kinetic-node";const GRID: [number, number] = [16, 16];const snap = (p: { x: number; y: number }) => ({ x: Math.round(p.x / GRID[0]) * GRID[0], y: Math.round(p.y / GRID[1]) * GRID[1] });@@ -732,6 +733,8 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv{ page: latest.current.pageId, targets: t, group, force: f, pages: docOf() },{onSuccess: (r) => {+ // Kinetic nodes render in this tab: they start now, each waiting for what feeds it.+ if (!group) window.dispatchEvent(new CustomEvent(KINETIC_RUN_EVENT, { detail: { canvasId: id, targets: t, ran: r.ran ?? [], errors: r.errors ?? [] } }));// The run saved the whole canvas as it was at `at`.savedRev.current = Math.max(savedRev.current, at);if (latest.current.rev === savedRev.current) setSaveState("saved");@@ -749,7 +752,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv};go(targets, force);},- [runMutate, docOf],+ [runMutate, docOf, id],);/**@@ -1281,7 +1284,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: CanvboardEngine={boardEngine}selectedCount={isMobile ? 0 : selected.length}running={runM.isPending}- canRun={generators.length > 0}+ canRun={generators.length > 0 || graph.nodes.some((n) => n.type === "kinetic")}mode={mode}ui={ui}/>diff --git a/src/components/canvas/canvas-list.tsx b/src/components/canvas/canvas-list.tsxindex 2845229b..9b724e02 100644--- a/src/components/canvas/canvas-list.tsx+++ b/src/components/canvas/canvas-list.tsx@@ -37,7 +37,7 @@ function CanvasCard({ c, onRename, onDelete }: { c: CanvasSummary; onRename: ()<div className="aspect-[16/10] overflow-hidden rounded-xl border bg-muted/50 transition-shadow group-hover/card:shadow-normal">{c.preview ? (c.preview.kind === "video" ? (- <video src={`${c.preview.url}#t=0.1`} muted playsInline preload="metadata" className="size-full object-cover" />+ <video src={`${c.preview.url}#t=0.1`} poster={c.preview.poster} muted playsInline preload="metadata" className="size-full object-cover" />) : (// eslint-disable-next-line @next/next/no-img-element<img src={c.preview.url} alt="" loading="lazy" className="size-full object-cover" />diff --git a/src/components/canvas/kinetic-node.tsx b/src/components/canvas/kinetic-node.tsxnew file mode 100644index 00000000..57d437d8--- /dev/null+++ b/src/components/canvas/kinetic-node.tsx@@ -0,0 +1,444 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";+import { ArrowUpRight, ChevronDown, Loader2, Play } from "lucide-react";+import Link from "next/link";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { toast } from "sonner";+import { renderKineticClip } from "@/components/kinetic/jobs";+import { MotionPlayer, useMotionInputs, usePlan, useScene } from "@/components/motion/player";+import { saveMotionResult } from "@/components/motion/save";+import { askToSignUp, useIsGuest } from "@/lib/api";+import { ancestors, descendants, tableRows, type Canvas, type CanvasGraph, type CanvasNode, type CanvasNodeData } from "@/lib/catalog/canvas";+import type { Generation } from "@/lib/catalog/types";+import { KINETIC_SCENES, entryBySlug, entryForRecipe, kineticHref, startRecipe, templateOf } from "@/lib/motion/kinetic-catalog";+import { DEFAULT_CLIP, docFiles, docWords } from "@/lib/motion/kinetic-doc";+import { recipeKey, type Recipe } from "@/lib/motion/recipe";+import { SIZE_LABELS } from "@/lib/motion/sizes";+import { templateSizes } from "@/lib/motion/template";+import { toastError } from "@/lib/refusals";+import { cn } from "@/lib/utils";+import { useEditorActions, useEditorGlobals, useEditorSnapshot } from "./canvas-context";++/**+ * The Canvas "Kinetic" node: a Kinetic Motion scene filled from what feeds it (a Text prompt fills the first field; a+ * Table fills field 1 from column 1, field 2 from column 2… and renders once per row), with a picture (the product, else+ * the logo) and a clip under the words where the scene takes one. It renders in this tab, one row at a time, saves each+ * row as a result, and records the run on the canvas for the Output nodes it feeds. A row whose recipe and result are+ * unchanged is kept.+ */++/** Its run starts on Run all too: the editor sends this event after it starts the server's part of the run. */+export const KINETIC_RUN_EVENT = "fuobe:kinetic-run";+export const KINETIC_ROWS_MAX = 50;++const KINETIC_FEATURE = "kinetic-canvas";++/** Kinetic nodes in a tab render one after another (each holds an encoder and a video while it renders). */+let turn: Promise<unknown> = Promise.resolve();+function inTurn<T>(fn: () => Promise<T>): Promise<T> {+ const next = turn.then(fn, fn);+ turn = next.catch(() => undefined);+ return next;+}++/** The node's recipe (a fresh one opens Big Number's showcase). */+export const nodeRecipe = (d: CanvasNodeData): Recipe => d.kinetic ?? startRecipe(entryBySlug("big-number")!);++interface Feeds {+ /** Rows of words (one row for a Text prompt). */+ rows: string[][];+ /** The table's columns, when a table feeds it. */+ columns: string[] | null;+ image: string | null;+ video: string | null;+ /** Upstream nodes still making something. */+ waiting: boolean;+}++/** What feeds the node now: its words, its picture and its clip (from input nodes, or from what other nodes made). */+export function feedsOf(graph: CanvasGraph, id: string, resultOf: (nodeId: string) => { url: string; kind: string; text?: string; busy: boolean } | null): Feeds {+ const nodes = new Map(graph.nodes.map((n) => [n.id, n]));+ const into = graph.edges.filter((e) => e.target === id);+ const src = (port: string) =>+ into+ .filter((e) => e.targetHandle === port)+ .map((e) => nodes.get(e.source))+ .filter((n): n is CanvasNode => !!n);+ let rows: string[][] = [];+ let columns: string[] | null = null;+ let waiting = false;+ const texts: string[] = [];+ for (const n of src("prompt")) {+ if (n.type === "table") {+ rows = tableRows(n);+ columns = n.data.columns ?? null;+ } else if (n.type === "prompt") texts.push(n.data.text ?? "");+ else {+ const r = resultOf(n.id);+ if (r?.busy) waiting = true;+ if (r?.text) texts.push(r.text);+ }+ }+ if (!rows.length && texts.some((t) => t.trim())) rows = [[texts.join(" ").trim()]];+ const media = (port: string, kind: string): string | null => {+ const n = src(port)[0];+ if (!n) return null;+ if (n.data.url && n.type === `${kind}-input`) return n.data.url;+ const r = resultOf(n.id);+ if (r?.busy) waiting = true;+ return r && r.kind === kind ? r.url : null;+ };+ return {+ rows,+ columns,+ image: media("images", "image"),+ video: media("video", "video"),+ waiting,+ };+}++/** The recipe of one row: its words in the fields by column, its picture and its clip. */+export function rowRecipe(base: Recipe, cells: string[] | null, image: string | null, video: string | null): Recipe {+ const entry = entryForRecipe(base);+ const t = entry ? templateOf(entry) : undefined;+ const fields = { ...base.fields };+ if (cells && t?.fields)+ t.fields.forEach((f, i) => {+ const v = (cells[i] ?? "").slice(0, f.max);+ if (v.trim()) fields[f.key] = v;+ else if (i < cells.length) delete fields[f.key];+ });+ const r: Recipe = { ...base, fields };+ if (image?.startsWith("/api/files/")) {+ if (t?.picture === "product") r.media = { ...(r.media ?? {}), product: image };+ else r.brand = { ...r.brand, logo: image };+ }+ if (video?.startsWith("/api/files/") && entry?.clip)+ r.layers = {+ ...(r.layers ?? {}),+ video: { ...(r.layers?.video ?? DEFAULT_CLIP), src: video },+ };+ return r;+}++const box = "h-11 w-full min-w-0 rounded-lg border bg-background px-2.5 text-[13px] outline-none focus-visible:ring-2 focus-visible:ring-ring nodrag";++export function KineticNodeBody({ id, data }: { id: string; data: CanvasNodeData }) {+ const actions = useEditorActions();+ const { canvasId, readOnly } = useEditorGlobals();+ const snap = useEditorSnapshot();+ const guest = useIsGuest();+ const qc = useQueryClient();+ const recipe = nodeRecipe(data);+ const entry = entryForRecipe(recipe) ?? KINETIC_SCENES[1];+ const t = templateOf(entry);+ const [hover, setHover] = useState(false);+ const [busy, setBusy] = useState<{ row: number; of: number } | null>(null);+ const abort = useRef<AbortController | null>(null);+ const inputs = useMotionInputs(recipe);+ const scene = useScene(recipe.scene);+ const plan = usePlan(scene, recipe, inputs);++ const resultOf = useCallback(+ (nodeId: string) => {+ const r = snap.views.get(nodeId)?.results;+ if (!r) return null;+ const o = r.outputs[0]?.o;+ return {+ url: o?.url ?? "",+ kind: o?.kind ?? "",+ text: o?.text,+ busy: r.state === "running" || r.state === "queued",+ };+ },+ [snap],+ );+ const feeds = useMemo(() => feedsOf(snap.graph, id, resultOf), [snap.graph, id, resultOf]);+ const set = (r: Recipe) => actions.update(id, { kinetic: r });+ // A node made before it had a recipe keeps the one it shows.+ useEffect(() => {+ if (!data.kinetic && !readOnly) actions.update(id, { kinetic: recipe });+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ const latest = useRef({ feeds, recipe, snap });+ useEffect(() => {+ latest.current = { feeds, recipe, snap };+ });++ /**+ * Waits for what feeds the node: every upstream node this run started (`ran`) must show a finished result in the+ * board's snapshot, which updates a render after the run's response. An upstream node that fails, or a wait past+ * ten minutes, stops the run with a message instead of rendering with an old result.+ */+ const waitForFeeds = useCallback(+ async (ran: string[], errors: { nodeId: string }[], signal: AbortSignal) => {+ const up = ancestors(latest.current.snap.graph, [id]);+ if (errors.some((x) => up.has(x.nodeId))) throw new Error("A node that feeds Kinetic couldn't run, so Kinetic didn't render");+ const started = ran.filter((x) => up.has(x));+ // The snapshot catches up with the run's response on the next render.+ await new Promise((r) => requestAnimationFrame(() => setTimeout(r, 0)));+ const until = Date.now() + 10 * 60_000;+ for (;;) {+ if (signal.aborted) throw new DOMException("Stopped", "AbortError");+ const views = latest.current.snap.views;+ const states = started.map((x) => views.get(x)?.results.state ?? "idle");+ if (states.some((s) => s === "failed" || s === "canceled")) throw new Error("A node that feeds Kinetic didn't finish, so Kinetic didn't render");+ if (states.every((s) => s === "succeeded") && !latest.current.feeds.waiting) return;+ if (Date.now() > until) throw new Error("What feeds Kinetic is still running. Run it again when it's done.");+ await new Promise((r) => setTimeout(r, 500));+ }+ },+ [id],+ );++ const runRows = useCallback(+ async (o: { ran?: string[]; errors?: { nodeId: string }[] } = {}) => {+ if (guest) return askToSignUp("run");+ if (abort.current) return;+ const ctl = new AbortController();+ abort.current = ctl;+ const ids: string[] = [];+ const sigs: string[] = [];+ const failed: number[] = [];+ const made: { base: Recipe | null } = { base: null };+ try {+ setBusy({ row: 0, of: 0 });+ await waitForFeeds(o.ran ?? [], o.errors ?? [], ctl.signal);+ // One Kinetic node renders at a time in a tab (each holds an encoder and a video while it renders).+ await inTurn(async () => {+ const { feeds: f } = latest.current;+ const base = (made.base = latest.current.recipe);+ const rows = f.rows.length ? f.rows.slice(0, KINETIC_ROWS_MAX) : [null];+ if (f.rows.length > KINETIC_ROWS_MAX) toast(`Kinetic renders the first ${KINETIC_ROWS_MAX} rows`);+ const view = qc.getQueryData<{+ canvas: Canvas;+ generations: Generation[];+ }>(["canvases", canvasId]);+ const prev = view?.canvas.runs[id];+ const live = new Set((view?.generations ?? []).filter((g) => g.status === "succeeded").map((g) => g.id));+ const name = view?.canvas.name ?? "Canvas";+ toast("Keep this tab open while Kinetic renders");+ for (const [i, cells] of rows.entries()) {+ if (ctl.signal.aborted) throw new DOMException("Stopped", "AbortError");+ const r = rowRecipe(base, cells, f.image, f.video);+ const sig = recipeKey(r);+ // A row kept from the last run by what it was made from (so a row added above doesn't render them all again).+ const at = prev?.rowSigs?.indexOf(sig) ?? -1;+ const kept = at >= 0 ? prev?.rows?.[at] : undefined;+ if (kept && live.has(kept) && !ids.includes(kept)) {+ ids.push(kept);+ sigs.push(sig);+ continue;+ }+ setBusy({ row: i + 1, of: rows.length });+ try {+ const clip = await renderKineticClip(r, { signal: ctl.signal });+ const e = entryForRecipe(r) ?? KINETIC_SCENES[1];+ const words = docWords({ recipe: r, logo: r.brand.logo ?? null }, e);+ const g = await saveMotionResult(+ { blob: clip.blob, type: clip.type, poster: clip.poster },+ {+ recipe: r,+ feature: KINETIC_FEATURE,+ title: `${name} · Kinetic · row ${i + 1}`,+ prompt: words.prompt,+ images: docFiles(r),+ },+ );+ ids.push(g.id);+ sigs.push(sig);+ } catch (e) {+ if ((e as Error).name === "AbortError") throw e;+ // A bad row (words too long, a clip that won't open) is skipped; the rest go on.+ failed.push(i + 1);+ toastError(e, `Row ${i + 1} didn't render`);+ }+ }+ });+ } catch (e) {+ if ((e as Error).name !== "AbortError") toastError(e, "Couldn't render this. Try again.");+ } finally {+ abort.current = null;+ setBusy(null);+ // What was made is kept on the canvas even when a row failed or the run was stopped.+ const base = made.base;+ if (ids.length && base) {+ try {+ const res = await fetch(`/api/canvases/${encodeURIComponent(canvasId)}/runs/${encodeURIComponent(id)}`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ sig: recipeKey(base),+ ids,+ rows: ids,+ rowSigs: sigs,+ }),+ });+ if (!res.ok) throw new Error(((await res.json().catch(() => ({}))) as { error?: string }).error ?? "Couldn't keep the run on this canvas");+ void qc.invalidateQueries({ queryKey: ["canvases", canvasId] });+ void qc.invalidateQueries({ queryKey: ["generations"] });+ if (!failed.length && !ctl.signal.aborted) toast.success(ids.length === 1 ? "Kinetic made 1 clip" : `Kinetic made ${ids.length} clips`);+ else if (failed.length) toast(`Kinetic made ${ids.length} of ${ids.length + failed.length} clips`);+ } catch (e) {+ toastError(e, "Couldn't keep the run on this canvas");+ }+ }+ }+ },+ [guest, qc, canvasId, id, waitForFeeds],+ );++ useEffect(() => {+ const on = (e: Event) => {+ const d = (+ e as CustomEvent<{+ canvasId: string;+ targets?: string[];+ ran?: string[];+ errors?: { nodeId: string }[];+ }>+ ).detail;+ if (d?.canvasId !== canvasId) return;+ const below = descendants(latest.current.snap.graph, [id]);+ if (!d.targets || d.targets.some((x) => x === id || below.has(x))) void runRows({ ran: d.ran, errors: d.errors });+ };+ window.addEventListener(KINETIC_RUN_EVENT, on);+ return () => window.removeEventListener(KINETIC_RUN_EVENT, on);+ }, [canvasId, id, runRows]);++ const fields = t.fields ?? [];+ const tableNote = feeds.columns+ ? fields+ .map((f, i) => `${feeds.columns?.[i] ?? `Column ${i + 1}`} → ${f.label}`)+ .slice(0, Math.max(1, Math.min(fields.length, feeds.columns.length)))+ .join(" · ")+ : null;+ return (+ <div className="space-y-2.5 p-3" onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)} onFocus={() => setHover(true)} onBlur={() => setHover(false)}>+ <div className="mx-auto w-full max-w-[200px]">+ <MotionPlayer plan={plan} sources={inputs.sources} size={recipe.size} duration={recipe.duration} fps={recipe.fps} label={`${entry.name} preview`} controls={false} active={hover} />+ </div>+ <label className="block text-[11px] font-medium text-muted-foreground">+ Scene+ <select+ value={entry.slug}+ disabled={readOnly}+ onChange={(e) => {+ const to = entryBySlug(e.target.value);+ if (to)+ set({+ ...startRecipe(to),+ brand: recipe.brand,+ size: templateSizes(templateOf(to)).includes(recipe.size as never) ? recipe.size : templateSizes(templateOf(to))[0],+ });+ }}+ className={cn(box, "mt-1")}+ >+ {KINETIC_SCENES.map((e) => (+ <option key={e.slug} value={e.slug}>+ {e.name}+ </option>+ ))}+ </select>+ </label>+ <button+ type="button"+ disabled={readOnly}+ onClick={() => (busy ? abort.current?.abort() : void runRows())}+ className="nodrag flex h-11 w-full items-center justify-center gap-2 rounded-lg bg-primary text-[13px] font-medium text-primary-foreground outline-none hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"+ data-kinetic-node-run={id}+ >+ {busy ? <Loader2 className="size-4 animate-spin" /> : <Play className="size-4" />}+ {busy ? (busy.of ? `Rendering row ${busy.row} of ${busy.of}` : "Waiting for what feeds it…") : feeds.rows.length > 1 ? `Run ${Math.min(KINETIC_ROWS_MAX, feeds.rows.length)} rows` : "Run"}+ </button>+ {tableNote && <p className="text-[11px] text-muted-foreground">{tableNote}</p>}+ {feeds.video && !entry.clip && <p className="text-[11px] text-muted-foreground">This scene doesn't take a clip</p>}+ <details className="group/set rounded-lg border">+ <summary className="nodrag flex h-11 cursor-pointer list-none items-center justify-between rounded-lg px-2.5 text-[13px] font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring [&::-webkit-details-marker]:hidden">+ Settings+ <ChevronDown className="size-4 text-muted-foreground transition-transform group-open/set:rotate-180 motion-reduce:transition-none" />+ </summary>+ <div className="space-y-2.5 px-2.5 pb-2.5">+ {fields.map((f, i) => (+ <label key={f.key} className="block text-[11px] font-medium text-muted-foreground">+ {f.label}+ {feeds.rows.length > 0 && i < (feeds.columns?.length ?? 1) ? <span className="font-normal"> · from {feeds.columns ? (feeds.columns[i] ?? `column ${i + 1}`) : "the text"}</span> : null}+ <input+ value={recipe.fields[f.key] ?? ""}+ maxLength={f.max}+ disabled={readOnly}+ onChange={(e) =>+ set({+ ...recipe,+ fields: { ...recipe.fields, [f.key]: e.target.value },+ })+ }+ className={cn(box, "mt-1")}+ />+ </label>+ ))}+ {(t.easy ?? []).map((g) => (+ <label key={g.id} className="block text-[11px] font-medium text-muted-foreground">+ {g.label}+ <select+ value={g.scene ? (recipe.scene.split("/")[1] ?? g.choices[0].id) : String(recipe.controls?.[g.id] ?? g.choices[0].id)}+ disabled={readOnly}+ onChange={(e) =>+ set(+ g.scene+ ? {+ ...recipe,+ scene: `${g.scene}/${e.target.value}`,+ controls: {+ ...recipe.controls,+ [g.id]: e.target.value,+ },+ }+ : {+ ...recipe,+ controls: {+ ...recipe.controls,+ [g.id]: e.target.value,+ },+ },+ )+ }+ className={cn(box, "mt-1")}+ >+ {g.choices.map((c) => (+ <option key={c.id} value={c.id}>+ {c.label}+ </option>+ ))}+ </select>+ </label>+ ))}+ <label className="block text-[11px] font-medium text-muted-foreground">+ Size+ <select+ value={typeof recipe.size === "string" ? recipe.size : templateSizes(t)[0]}+ disabled={readOnly}+ onChange={(e) => set({ ...recipe, size: e.target.value as Recipe["size"] })}+ className={cn(box, "mt-1")}+ >+ {templateSizes(t).map((s) => (+ <option key={s} value={s}>+ {SIZE_LABELS[s]}+ </option>+ ))}+ </select>+ </label>+ <Link+ href={kineticHref(entry, entry.slug === "end-card" ? (recipe.scene.split("/")[1] ?? null) : null)}+ className="nodrag inline-flex h-11 items-center gap-1.5 rounded-lg text-[13px] font-medium text-foreground underline-offset-4 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring"+ >+ Open in Kinetic+ <ArrowUpRight className="size-4" />+ </Link>+ </div>+ </details>+ </div>+ );+}diff --git a/src/components/canvas/node-icon.tsx b/src/components/canvas/node-icon.tsxindex 6ef456aa..d222b01e 100644--- a/src/components/canvas/node-icon.tsx+++ b/src/components/canvas/node-icon.tsx@@ -24,6 +24,7 @@ import {ImageIcon,Languages,LayoutDashboard,+ LetterText,MessageSquareText,Mic2,MonitorPlay,@@ -68,6 +69,8 @@ export const ICONS: Record<string, LucideIcon> = {UserRound,Languages,Table,+ // Kinetic+ LetterText,// Camera path and Fly aroundOrbit,Rotate3d,diff --git a/src/components/canvas/nodes.tsx b/src/components/canvas/nodes.tsxindex 3f9b6b1f..7d22dc76 100644--- a/src/components/canvas/nodes.tsx+++ b/src/components/canvas/nodes.tsx@@ -128,6 +128,7 @@ import { layoutCanvas } from "@/lib/catalog/plan";import { getModel } from "@/lib/catalog";import type { EditorCanvas } from "@/components/studio/layout-editor";import { BOARD_NODE_TYPES, type BoardType } from "./board";+import { KineticNodeBody } from "./kinetic-node";import { ExactOrbitControls } from "@/components/exact-orbit-controls";import { PATH_PRESETS } from "@/lib/camera-path";import { exactDefaults } from "@/lib/exact-orbit";@@ -528,6 +529,7 @@ function OutputThumb({ o, onOpen, className, large }: { o: OutputFile; onOpen: ({o.kind === "video" ? (<videosrc={`${o.url}#t=0.1`}+ poster={typeof o.meta?.poster === "string" ? o.meta.poster : undefined}mutedloopplaysInline@@ -1261,6 +1263,25 @@ export function CameraPathFields({ data, onChange, disabled, label }: { data: Ca}/** Camera path: a preset move, or an exact orbit by its numbers, for Fly around nodes to follow. */+// ---------------------------------------------------------------------------+// Kinetic: words as motion graphics, rendered in this tab once per row++const KineticNode = memo(function KineticNode({ id, type, data, selected }: NodeProps<FlowNode>) {+ const v = useNodeView(id);+ const node = useMemo(() => asNode(id, "kinetic", data), [id, data]);+ const ports = useMemo(() => inputPorts(node), [node]);+ return (+ <NodeShell id={id} type={type as CanvasNodeType} data={data} selected={!!selected} out="video" width={280}>+ <div className="border-b py-1">+ {ports.map((p) => (+ <InPort key={p.id} port={p} count={v.counts[p.id] ?? 0} />+ ))}+ </div>+ <KineticNodeBody id={id} data={data} />+ </NodeShell>+ );+}, sameNodeProps);+const CameraPathNode = memo(function CameraPathNode({ id, type, data, selected }: NodeProps<FlowNode>) {const actions = useEditorActions();const { readOnly } = useEditorGlobals();@@ -1706,7 +1727,7 @@ const OutputNode = memo(function OutputNode({ id, type, data, selected }: NodePrfunction SourcePreview({ node }: { node: Source }) {const actions = useEditorActions();const r = useNodeResults(node.id);- if (isGenerator(node)) {+ if (isGenerator(node) || node.type === "kinetic") {if (r.outputs.length) return <OutputThumb o={r.outputs[0].o} onOpen={() => actions.open(node.id, 0)} large />;if (r.state !== "idle") return <Results id={node.id} r={r} compact />;return <div className="grid h-20 place-items-center rounded-lg bg-muted text-[11px] text-muted-foreground">Not run yet</div>;@@ -2015,6 +2036,7 @@ export const NODE_TYPES = {concat: GeneratorNode,restore: GeneratorNode,"fly-around": GeneratorNode,+ kinetic: KineticNode,"camera-path": CameraPathNode,table: TableNode,layout: LayoutNode,diff --git a/src/components/kinetic/clip-picker.tsx b/src/components/kinetic/clip-picker.tsxnew file mode 100644index 00000000..c31d6fb5--- /dev/null+++ b/src/components/kinetic/clip-picker.tsx@@ -0,0 +1,216 @@+"use client";++import { Film, Loader2, Upload, X } from "lucide-react";+import { useEffect, useMemo, useRef, useState } from "react";+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";+import { askToSignUp, uploadFile, useAskBeforeUpload, useGenerations, useIsGuest, useUploads } from "@/lib/api";+import { DEFAULT_CLIP, setClip, type KineticDoc } from "@/lib/motion/kinetic-doc";+import type { VideoLayer } from "@/lib/motion/recipe";+import { toastError } from "@/lib/refusals";+import { Choices, iconButton, Segmented, sheetClass, SliderField } from "./controls";+import type { ClipInputs } from "./preview";+import { useTrackSlider } from "./pro-panels";+import type { TimeStore } from "./time-store";+import type { KineticEditor } from "./use-editor";++/**+ * The clip under the words (five scenes take one): the person's own video results to pick from, an upload for whoever+ * can add files (the owner, an account with its own GPU or key; it goes through the normal upload rules), and how the+ * clip sits: where it starts, cover or contain, a dim and a scrim in the ground colour. Clips are saved without sound.+ */++const SCRIMS: { id: VideoLayer["scrim"]; label: string }[] = [+ { id: "none", label: "None" },+ { id: "bottom", label: "Bottom" },+ { id: "top", label: "Top" },+ { id: "full", label: "Full" },+];++/** A clip's first frame, its <video> made only once the tile scrolls into view (a long list never opens them all). */+function LazyClip({ url }: { url: string }) {+ const ref = useRef<HTMLSpanElement>(null);+ const [near, setNear] = useState(false);+ useEffect(() => {+ const el = ref.current;+ if (!el || near) return;+ // Every browser Kinetic runs in has IntersectionObserver.+ const io = new IntersectionObserver(([e]) => e.isIntersecting && setNear(true), { rootMargin: "120px" });+ io.observe(el);+ return () => io.disconnect();+ }, [near]);+ return <span ref={ref} className="block size-full">{near && <video src={`${url}#t=0.1`} muted playsInline preload="metadata" className="size-full object-contain" />}</span>;+}++const when = (ms: number) => new Date(ms).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });++function Picker({ open, onClose, side, onPick }: { open: boolean; onClose: () => void; side: "bottom" | "right"; onPick: (url: string) => void }) {+ const guest = useIsGuest();+ const askFirst = useAskBeforeUpload();+ const list = useGenerations({ kinds: ["video"], statuses: ["succeeded"], limit: 48 });+ const items = useMemo(() => (guest ? [] : (list.data ?? []).filter((g) => g.status === "succeeded" && g.outputs[0]?.kind === "video" && g.outputs[0].url.startsWith("/api/files/"))), [list.data, guest]);+ // The person's own uploaded clips (the Library's Uploads), after their results.+ const uploads = useUploads("video");+ const own = useMemo(() => (guest ? [] : (uploads.data?.pages.flat() ?? []).filter((a) => a.url.startsWith("/api/files/") && !items.some((g) => g.outputs[0].url === a.url)).slice(0, 24)), [uploads.data, items, guest]);+ const file = useRef<HTMLInputElement>(null);+ const [uploading, setUploading] = useState(false);+ return (+ <Sheet open={open} onOpenChange={(v) => !v && onClose()}>+ <SheetContent side={side} showCloseButton={false} className={sheetClass} data-kinetic-sheet="clip">+ <SheetHeader className="flex-row items-start gap-2 pb-3">+ <div className="min-w-0 flex-1">+ <SheetTitle>Pick a clip</SheetTitle>+ <SheetDescription className="text-[13px]">Your words play over it. Kinetic clips are saved without sound.</SheetDescription>+ </div>+ <button type="button" onClick={onClose} aria-label="Close" className={iconButton}>+ <X className="size-4" />+ </button>+ </SheetHeader>+ <div className="min-w-0 space-y-3 px-4 pb-4">+ <button+ type="button"+ data-kinetic-upload-clip+ disabled={uploading}+ onClick={() => {+ if (askFirst()) return;+ file.current?.click();+ }}+ className="flex h-12 w-full items-center justify-center gap-2 rounded-xl border border-dashed text-[14px] font-medium outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60"+ >+ {uploading ? <Loader2 className="size-4 animate-spin" /> : <Upload className="size-4" />} Upload a clip+ </button>+ <input+ ref={file}+ type="file"+ accept="video/mp4,video/webm,video/quicktime"+ className="sr-only"+ tabIndex={-1}+ aria-hidden+ onChange={async (e) => {+ const f = e.target.files?.[0];+ e.target.value = "";+ if (!f) return;+ setUploading(true);+ try {+ const a = await uploadFile(f);+ onPick(a.url);+ onClose();+ } catch (err) {+ toastError(err, "Couldn't add that clip. Try another.");+ } finally {+ setUploading(false);+ }+ }}+ />+ {items.length + own.length > 0 ? (+ <ul className="grid grid-cols-2 gap-2 sm:grid-cols-3" data-kinetic-clips>+ {own.map((a) => (+ <li key={a.id} className="min-w-0">+ <button+ type="button"+ data-kinetic-clip={a.id}+ onClick={() => {+ onPick(a.url);+ onClose();+ }}+ aria-label={`Use ${(a.name ?? "your clip").slice(0, 80)}`}+ className="relative block aspect-video w-full overflow-hidden rounded-xl bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <LazyClip url={a.url} />+ </button>+ <p className="mt-1 truncate text-[12px] text-muted-foreground">{a.name ?? "Your clip"}</p>+ </li>+ ))}+ {items.map((g) => {+ const o = g.outputs[0];+ const poster = typeof o.meta?.poster === "string" ? o.meta.poster : undefined;+ return (+ <li key={g.id} className="min-w-0">+ <button+ type="button"+ data-kinetic-clip={g.id}+ onClick={() => {+ onPick(o.url);+ onClose();+ }}+ aria-label={`Use ${(g.request.title ?? g.request.prompt ?? "this clip").slice(0, 80)}`}+ className="relative block aspect-video w-full overflow-hidden rounded-xl bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {poster ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={poster} alt="" loading="lazy" className="size-full object-contain" />+ ) : (+ <LazyClip url={o.url} />+ )}+ </button>+ <p className="mt-1 truncate text-[12px] text-muted-foreground">{g.request.title ?? g.request.prompt ?? "Clip"}</p>+ <p className="truncate text-[11px] text-muted-foreground/80 tabular-nums">+ {when(g.createdAt)}+ {o.width && o.height ? ` · ${o.width}×${o.height}` : ""}+ </p>+ </li>+ );+ })}+ </ul>+ ) : (+ <p className="text-[13px] text-muted-foreground">Your clips and video results show here to pick from.</p>+ )}+ </div>+ </SheetContent>+ </Sheet>+ );+}++export function ClipControl({ doc, editor, time, clip, side, pro }: { doc: KineticDoc; editor: Pick<KineticEditor, "apply" | "end">; time: TimeStore; clip: ClipInputs; side: "bottom" | "right"; pro: boolean }) {+ const guest = useIsGuest();+ const [open, setOpen] = useState(false);+ const layer = doc.recipe.layers?.video;+ const track = useTrackSlider({ doc, editor, time });+ const set = (x: Partial<VideoLayer>, gesture = false) => editor.apply((d) => (d.recipe.layers?.video ? setClip(d, { ...d.recipe.layers.video, ...x }) : d), { gesture });+ const dim = track("clip.dim", layer?.dim ?? 0, (r, v) => (r.layers?.video ? { ...r, layers: { ...r.layers, video: { ...r.layers.video, dim: Math.round(v * 100) / 100 } } } : r));+ const maxFrom = Math.max(0, Math.min(600, (clip.info?.duration ?? 0) - 0.1));+ return (+ <div className="min-w-0 space-y-3" data-kinetic-clip-control>+ <div className="min-w-0">+ <p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Clip</p>+ <div className="flex min-w-0 items-center gap-2">+ {layer && (+ <span className="relative grid h-11 w-16 shrink-0 place-items-center overflow-hidden rounded-lg bg-muted">+ <video src={layer.src} muted playsInline preload="metadata" className="size-full object-cover" aria-hidden />+ </span>+ )}+ <button+ type="button"+ onClick={() => (guest ? askToSignUp("upload") : setOpen(true))}+ className="inline-flex h-11 min-w-0 items-center gap-2 rounded-full bg-secondary px-4 text-[13px] font-medium outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"+ >+ <Film className="size-4 shrink-0" /> <span className="truncate">{layer ? "Change clip" : "Pick a clip"}</span>+ </button>+ {layer && (+ <button type="button" onClick={() => editor.apply((d) => setClip(d, null))} className="h-11 shrink-0 rounded-full px-3 text-[13px] font-medium text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring">+ Remove+ </button>+ )}+ </div>+ {clip.failed && <p className="mt-1 text-[12px] text-destructive">Pick the clip again</p>}+ <p className="mt-1 text-[11px] text-muted-foreground md:text-[12px]">Kinetic clips are saved without sound.</p>+ </div>+ {layer && (+ <>+ <SliderField label="Start at" unit="s" display={(v) => `${v.toFixed(1)} s`} value={layer.from} min={0} max={Math.max(0.1, maxFrom)} step={0.1} disabled={maxFrom <= 0} onChange={(v) => set({ from: v }, true)} onEnd={editor.end} />+ <Segmented+ label="Fit"+ choices={[+ { id: "cover", label: "Cover" },+ { id: "contain", label: "Contain" },+ ]}+ value={layer.fit}+ onChange={(fit) => set({ fit })}+ />+ <SliderField label="Dim" unit="%" display={(v) => `${Math.round(v * 100)} %`} min={0} max={0.8} step={0.01} scale={100} {...dim} keyButton={pro ? dim.keyButton : undefined} />+ <Choices label="Scrim" choices={SCRIMS} value={layer.scrim} onChange={(scrim) => set({ scrim })} />+ </>+ )}+ <Picker open={open} onClose={() => setOpen(false)} side={side} onPick={(src) => editor.apply((d) => setClip(d, { ...(d.recipe.layers?.video ?? DEFAULT_CLIP), src, from: 0 }))} />+ </div>+ );+}diff --git a/src/components/kinetic/controls.tsx b/src/components/kinetic/controls.tsxnew file mode 100644index 00000000..8c87a805--- /dev/null+++ b/src/components/kinetic/controls.tsx@@ -0,0 +1,246 @@+"use client";++import { ChevronDown, Diamond } from "lucide-react";+import { useId, useState } from "react";+import { cn } from "@/lib/utils";++/**+ * Kinetic's small controls: segmented choices, a slider with its number field (and, for the numbers a track can+ * animate, a key button), and a collapsible panel. Every target is at least 44 px; sliders get a 44 px hit area.+ */++export const chipClass = (on: boolean) =>+ cn(+ "inline-flex h-11 min-w-0 items-center justify-center rounded-full px-3.5 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring",+ on ? "bg-foreground text-background" : "bg-secondary text-secondary-foreground hover:bg-accent",+ );++export const iconButton =+ "grid size-11 shrink-0 place-items-center rounded-full text-foreground outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40";++/** One choice of several (a radio group of chips). `value` null shows none chosen (a Pro value moved it). */+export function Choices<T extends string>({+ label,+ choices,+ value,+ onChange,+ note,+ className,+}: {+ label: string;+ choices: readonly { id: T; label: string }[];+ value: T | null;+ onChange: (v: T) => void;+ note?: string;+ className?: string;+}) {+ return (+ <div className={cn("min-w-0", className)}>+ <p className="mb-1.5 text-[12px] font-medium text-muted-foreground">+ {label}+ {note && <span className="font-normal"> · {note}</span>}+ </p>+ <div role="radiogroup" aria-label={label} className="flex min-w-0 flex-wrap gap-1.5">+ {choices.map((c) => (+ <button key={c.id} type="button" role="radio" aria-checked={value === c.id} onClick={() => onChange(c.id)} className={chipClass(value === c.id)}>+ {c.label}+ </button>+ ))}+ </div>+ </div>+ );+}++/** A segmented control: equal parts in one rounded track. */+export function Segmented<T extends string>({+ label,+ choices,+ value,+ onChange,+ hideLabel,+}: {+ label: string;+ choices: readonly { id: T; label: string }[];+ value: T | null;+ onChange: (v: T) => void;+ hideLabel?: boolean;+}) {+ return (+ <div className="min-w-0">+ {!hideLabel && <p className="mb-1.5 text-[12px] font-medium text-muted-foreground">{label}</p>}+ <div role="radiogroup" aria-label={label} className="grid min-w-0 auto-cols-fr grid-flow-col gap-0.5 rounded-full bg-secondary p-0.5">+ {choices.map((c) => (+ <button+ key={c.id}+ type="button"+ role="radio"+ aria-checked={value === c.id}+ onClick={() => onChange(c.id)}+ className={cn(+ "h-11 min-w-0 truncate rounded-full px-2 text-[13px] font-medium transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring",+ value === c.id ? "bg-foreground text-background" : "text-muted-foreground hover:text-foreground",+ )}+ >+ {c.label}+ </button>+ ))}+ </div>+ </div>+ );+}++const round = (v: number, step: number) => {+ const d = Math.max(0, Math.ceil(-Math.log10(step) - 1e-9));+ return Number(v.toFixed(d));+};++export interface SliderFieldProps {+ label: string;+ /** The value in words for screen readers ("x1.00", "Off"). */+ display?: (v: number) => string;+ /** The unit shown inside the number field ("s", "°", "%"). */+ unit?: string;+ value: number;+ min: number;+ max: number;+ step: number;+ /** A drag or a typed number: every change of one gesture is one undo step (`end` closes it). */+ onChange: (v: number) => void;+ onEnd?: () => void;+ /** The number field shows and takes the value in its own scale (percent: × 100). */+ scale?: number;+ /** Words at the two ends of the slider. */+ ends?: [string, string];+ /** A key button (parameter tracks): its label, and whether a key sits at the playhead. */+ keyButton?: { label: string; on: boolean; onPress: () => void };+ /** A line under it (where an Easy value came from, a limit). */+ note?: string;+ disabled?: boolean;+ /** The slider runs from max on the left to min on the right (Pace: Calmer to Punchier). */+ reverse?: boolean;+}++/** A slider with a number field beside it (44 px each; the field clamps on blur, Enter applies). */+export function SliderField({ label, display, unit, value, min, max, step, onChange, onEnd, scale = 1, ends, keyButton, note, disabled, reverse }: SliderFieldProps) {+ const id = useId();+ const shown = round(value * scale, step * scale);+ // What is typed while the field has focus (null: the field shows the value).+ const [typed, setTyped] = useState<string | null>(null);+ const text = typed ?? String(shown);+ const commit = () => {+ const n = Number(text.replace(",", ".").replace(/[^\d.+-]/g, ""));+ setTyped(null);+ if (!Number.isFinite(n) || typed === null) return;+ const v = Math.min(max, Math.max(min, n / scale));+ onChange(round(v, step));+ onEnd?.();+ };+ return (+ <div className={cn("min-w-0", disabled && "opacity-50")}>+ <label htmlFor={id} className="block truncate text-[12px] font-medium text-muted-foreground">+ {label}+ </label>+ <div className="flex min-w-0 items-start gap-1.5">+ <div className="min-w-0 flex-1">+ <input+ id={id}+ type="range"+ min={min}+ max={max}+ step={step}+ value={Math.min(max, Math.max(min, value))}+ disabled={disabled}+ dir={reverse ? "rtl" : undefined}+ onChange={(e) => onChange(Number(e.target.value))}+ onPointerUp={onEnd}+ onKeyUp={onEnd}+ onBlur={onEnd}+ aria-valuetext={display?.(value)}+ className="k-range block h-11 w-full min-w-0 cursor-pointer"+ style={+ {+ "--fill": `${((Math.min(max, Math.max(min, value)) - min) / (max - min || 1)) * 100}%`,+ } as React.CSSProperties+ }+ />+ {ends && (+ <div className="-mt-2 flex justify-between text-[12px] text-muted-foreground" aria-hidden>+ <span>{ends[0]}</span>+ <span>{ends[1]}</span>+ </div>+ )}+ </div>+ <div className="relative w-[4.5rem] shrink-0">+ <input+ type="text"+ inputMode="decimal"+ aria-label={`${label} value`}+ value={text}+ disabled={disabled}+ onFocus={() => setTyped(String(shown))}+ onChange={(e) => setTyped(e.target.value)}+ onBlur={commit}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ commit();+ }+ }}+ className={cn(+ "h-11 w-full rounded-xl border bg-background pl-2 text-right text-[13px] tabular-nums outline-none focus-visible:border-primary focus-visible:ring-2 focus-visible:ring-ring",+ unit ? "pr-6" : "pr-2",+ )}+ />+ {unit && (+ <span className="pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 text-[12px] text-muted-foreground" aria-hidden>+ {unit}+ </span>+ )}+ </div>+ {keyButton && (+ <button+ type="button"+ aria-label={keyButton.label}+ aria-pressed={keyButton.on}+ onClick={keyButton.onPress}+ disabled={disabled}+ className={cn(iconButton, keyButton.on ? "text-primary" : "text-muted-foreground")}+ >+ <Diamond className={cn("size-4", keyButton.on && "fill-current")} />+ </button>+ )}+ </div>+ {note && <p className="mt-0.5 text-[12px] text-muted-foreground">{note}</p>}+ </div>+ );+}++/** A collapsible panel with a 44 px header. */+export function Panel({ title, summary, open, onOpen, children, id }: { title: string; summary?: string; open: boolean; onOpen: (v: boolean) => void; children: React.ReactNode; id: string }) {+ return (+ <section className="min-w-0 rounded-2xl border bg-card" data-kinetic-panel={id}>+ <h3 className="m-0">+ <button+ type="button"+ aria-expanded={open}+ aria-controls={`kinetic-panel-${id}`}+ onClick={() => onOpen(!open)}+ className="flex min-h-11 w-full min-w-0 items-center gap-2 rounded-2xl px-3.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <span className="text-[14px] font-medium">{title}</span>+ {summary && <span className="min-w-0 flex-1 truncate text-right text-[12px] text-muted-foreground">{summary}</span>}+ <ChevronDown className={cn("size-4 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none", !summary && "ml-auto", open && "rotate-180")} />+ </button>+ </h3>+ {open && (+ <div id={`kinetic-panel-${id}`} className="min-w-0 space-y-4 px-3.5 pt-1 pb-4">+ {children}+ </div>+ )}+ </section>+ );+}++/** The sheets' shared classes: a bottom sheet on phones, a right-hand sheet from 768 px; no slide with reduced motion. */+export const sheetClass =+ "max-h-[88svh] gap-0 overflow-y-auto rounded-t-[22px] pb-[max(1rem,env(safe-area-inset-bottom))] motion-reduce:animate-none motion-reduce:transition-none md:max-h-none md:rounded-none md:data-[side=right]:w-[420px] md:data-[side=right]:max-w-[420px]";diff --git a/src/components/kinetic/curve-graph.tsx b/src/components/kinetic/curve-graph.tsxnew file mode 100644index 00000000..12b6864f--- /dev/null+++ b/src/components/kinetic/curve-graph.tsx@@ -0,0 +1,188 @@+"use client";++import { useMemo, useRef, useState } from "react";+import { warpOf, type WarpKeys } from "@/lib/motion/edit";+import { cn } from "@/lib/utils";++/**+ * A motion group's timing curve: its warp keys on a square graph (time across, progress up). It shows only the+ * recipe's keys, joined the way the scene reads them. Tap empty space to add a key, drag a key to move it (applied on+ * release, as one step), Delete removes the selected key (never the two ends), and the arrow keys move it by 0.01, or+ * 0.1 with Shift. `under` draws a sampled line behind (the Camera group: its zoom over time).+ */++const PAD = 16;+const MAX_KEYS = 8;+const GAP = 0.01;++const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));+const r4 = (v: number) => Math.round(v * 1e4) / 1e4;++/** A key moved to (u, p), kept strictly between its neighbours in u and between their p. */+function moved(keys: WarpKeys, i: number, u: number, p: number): WarpKeys {+ if (i <= 0 || i >= keys.length - 1) return keys;+ const lo = keys[i - 1];+ const hi = keys[i + 1];+ const nu = r4(clamp(u, lo[0] + GAP, hi[0] - GAP));+ const np = r4(clamp(p, lo[1], hi[1]));+ if (!(nu > lo[0] && nu < hi[0])) return keys;+ return keys.map((k, j) => (j === i ? [nu, np] : k)) as WarpKeys;+}++/** The keys with one added at (u, p) in order (p held between its neighbours'), and its index; null when full. */+export function addKey(keys: WarpKeys, u: number, p: number): { keys: WarpKeys; index: number } | null {+ if (keys.length >= MAX_KEYS || u <= GAP || u >= 1 - GAP) return null;+ const i = keys.findIndex((k) => k[0] > u);+ if (i <= 0) return null;+ const lo = keys[i - 1];+ const hi = keys[i];+ if (u - lo[0] < GAP || hi[0] - u < GAP) return null;+ const next = [...keys.slice(0, i), [r4(u), r4(clamp(p, lo[1], hi[1]))], ...keys.slice(i)] as WarpKeys;+ return { keys: next, index: i };+}++export function CurveGraph({ keys, onChange, label, under, underLabel }: { keys: WarpKeys; onChange: (keys: WarpKeys) => void; label: string; under?: number[]; underLabel?: string }) {+ const [draft, setDraft] = useState<WarpKeys | null>(null);+ const [picked, setSel] = useState<number | null>(null);+ // A selection past the keys there are now (after an undo) selects nothing.+ const sel = picked !== null && picked < keys.length ? picked : null;+ const svg = useRef<SVGSVGElement>(null);+ const drag = useRef<{ i: number; moved: boolean } | null>(null);+ const shown = draft ?? keys;+ const S = 280;+ const inner = S - PAD * 2;+ const x = (u: number) => PAD + u * inner;+ const y = (p: number) => PAD + (1 - p) * inner;++ const path = useMemo(() => {+ const w = warpOf(shown);+ const pts: string[] = [];+ for (let i = 0; i <= 64; i++) {+ const u = i / 64;+ pts.push(`${i ? "L" : "M"}${x(u).toFixed(1)},${y(w(u)).toFixed(1)}`);+ }+ return pts.join(" ");+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [shown]);++ const underPath = useMemo(() => {+ if (!under?.length) return null;+ const lo = Math.min(...under);+ const hi = Math.max(...under);+ const span = hi - lo || 1;+ return under.map((v, i) => `${i ? "L" : "M"}${x(i / (under.length - 1)).toFixed(1)},${y(hi === lo ? 0.5 : (v - lo) / span).toFixed(1)}`).join(" ");+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [under]);++ const at = (e: { clientX: number; clientY: number }) => {+ const box = svg.current!.getBoundingClientRect();+ const k = S / box.width;+ return { u: clamp(((e.clientX - box.left) * k - PAD) / inner, 0, 1), p: clamp(1 - ((e.clientY - box.top) * k - PAD) / inner, 0, 1) };+ };++ const nudge = (du: number, dp: number) => {+ if (sel === null) return;+ const k = keys[sel];+ const next = moved(keys, sel, k[0] + du, k[1] + dp);+ if (next !== keys) onChange(next);+ };++ return (+ <div className="min-w-0">+ <svg+ ref={svg}+ viewBox={`0 0 ${S} ${S}`}+ role="group"+ aria-label={label}+ tabIndex={0}+ className="block aspect-square w-full max-w-[360px] min-w-[280px] touch-none rounded-2xl bg-secondary outline-none select-none focus-visible:ring-2 focus-visible:ring-ring"+ onPointerDown={(e) => {+ if ((e.target as Element).getAttribute("data-key") !== null) return;+ const { u, p } = at(e);+ const added = addKey(keys, u, p);+ if (added) {+ onChange(added.keys);+ setSel(added.index);+ }+ }}+ onPointerMove={(e) => {+ const d = drag.current;+ if (!d) return;+ const { u, p } = at(e);+ d.moved = true;+ setDraft((cur) => moved(cur ?? keys, d.i, u, p));+ }}+ onPointerUp={() => {+ const d = drag.current;+ drag.current = null;+ if (d?.moved && draft) onChange(draft);+ setDraft(null);+ }}+ onKeyDown={(e) => {+ const step = e.shiftKey ? 0.1 : 0.01;+ if (e.key === "ArrowLeft") nudge(-step, 0);+ else if (e.key === "ArrowRight") nudge(step, 0);+ else if (e.key === "ArrowUp") nudge(0, step);+ else if (e.key === "ArrowDown") nudge(0, -step);+ else if ((e.key === "Delete" || e.key === "Backspace") && sel !== null && sel > 0 && sel < keys.length - 1) {+ onChange(keys.filter((_, j) => j !== sel) as WarpKeys);+ setSel(null);+ } else return;+ e.preventDefault();+ }}+ >+ {[0.25, 0.5, 0.75].map((g) => (+ <g key={g} className="text-border" stroke="currentColor" strokeWidth={1}>+ <line x1={x(g)} x2={x(g)} y1={y(0)} y2={y(1)} />+ <line x1={x(0)} x2={x(1)} y1={y(g)} y2={y(g)} />+ </g>+ ))}+ <rect x={x(0)} y={y(1)} width={inner} height={inner} fill="none" stroke="currentColor" className="text-border" />+ {underPath && <path d={underPath} fill="none" stroke="currentColor" strokeWidth={1.5} strokeDasharray="3 4" className="text-muted-foreground" />}+ <path d={path} fill="none" stroke="currentColor" strokeWidth={2.5} className="text-foreground" />+ {shown.map((k, i) => {+ const end = i === 0 || i === shown.length - 1;+ return (+ <g key={i}>+ <circle+ data-key={i}+ cx={x(k[0])}+ cy={y(k[1])}+ r={22}+ fill="transparent"+ className={end ? "cursor-default" : "cursor-grab"}+ onPointerDown={(e) => {+ e.stopPropagation();+ setSel(i);+ if (end) return;+ (e.currentTarget.ownerSVGElement as SVGSVGElement).setPointerCapture(e.pointerId);+ drag.current = { i, moved: false };+ }}+ />+ <circle cx={x(k[0])} cy={y(k[1])} r={6} pointerEvents="none" className={cn(sel === i ? "fill-primary" : "fill-foreground")} stroke="var(--background)" strokeWidth={2} />+ </g>+ );+ })}+ </svg>+ <div className="mt-1 flex min-w-0 justify-between text-[11px] text-muted-foreground md:text-[12px]">+ <span>{underLabel ?? "Time across, progress up"}</span>+ <span className="tabular-nums">{shown.length} keys</span>+ </div>+ <div className="mt-2 flex items-center gap-2">+ <button+ type="button"+ disabled={sel === null || sel === 0 || sel === keys.length - 1}+ onClick={() => {+ if (sel === null) return;+ onChange(keys.filter((_, j) => j !== sel) as WarpKeys);+ setSel(null);+ }}+ className="h-11 rounded-full bg-secondary px-4 text-[13px] font-medium outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-40"+ >+ Delete key+ </button>+ <p className="min-w-0 text-[11px] text-muted-foreground md:text-[12px]">Tap the graph to add a key; drag to move it.</p>+ </div>+ </div>+ );+}diff --git a/src/components/kinetic/draft.ts b/src/components/kinetic/draft.tsnew file mode 100644index 00000000..fcbb0373--- /dev/null+++ b/src/components/kinetic/draft.ts@@ -0,0 +1,49 @@+/**+ * Kinetic's local draft and per-viewer choices, kept in this browser only (every read and write wrapped: a private+ * window or blocked storage just means no draft, and the page works the same). A draft is the current recipe per+ * viewer and scene, so a reload brings it back.+ */++import { RecipeSchema, type Recipe } from "@/lib/motion/recipe";++const get = (key: string): string | null => {+ try {+ return window.localStorage.getItem(key);+ } catch {+ return null;+ }+};++const put = (key: string, value: string | null): void => {+ try {+ if (value === null) window.localStorage.removeItem(key);+ else window.localStorage.setItem(key, value);+ } catch {}+};++export const draftKey = (viewer: string, slug: string) => `kinetic:draft:${viewer}:${slug}`;++export function readDraft(viewer: string, slug: string): { recipe: Recipe; logo: string | null } | null {+ const raw = get(draftKey(viewer, slug));+ if (!raw) return null;+ try {+ const v = JSON.parse(raw) as { recipe?: unknown; logo?: unknown };+ const r = RecipeSchema.safeParse(v.recipe);+ if (!r.success) return null;+ return { recipe: r.data, logo: typeof v.logo === "string" ? v.logo : null };+ } catch {+ return null;+ }+}++export const writeDraft = (viewer: string, slug: string, d: { recipe: Recipe; logo: string | null }) => put(draftKey(viewer, slug), JSON.stringify(d));++export const dropDraft = (viewer: string, slug: string) => put(draftKey(viewer, slug), null);++/** A small per-viewer choice (Easy or Pro, the preview mode). */+export function readChoice<T extends string>(key: string, allowed: readonly T[], fallback: T): T {+ const v = get(`kinetic:${key}`);+ return v && (allowed as readonly string[]).includes(v) ? (v as T) : fallback;+}++export const writeChoice = (key: string, value: string) => put(`kinetic:${key}`, value);diff --git a/src/components/kinetic/editor-bar.tsx b/src/components/kinetic/editor-bar.tsxnew file mode 100644index 00000000..55372b1e--- /dev/null+++ b/src/components/kinetic/editor-bar.tsx@@ -0,0 +1,85 @@+"use client";++import { ArrowLeft, Check, Expand, LayoutGrid, MoreHorizontal, Redo2, Shrink, Undo2 } from "lucide-react";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { KINETIC_SCENES, type KineticEntry } from "@/lib/motion/kinetic-catalog";+import { cn } from "@/lib/utils";+import { iconButton } from "./controls";++/** The editor's bar: back to all scenes, the scene's name, Undo and Redo, Large preview (desktop) and More. */+export function EditorBar({+ entry,+ onBack,+ onScene,+ canUndo,+ canRedo,+ onUndo,+ onRedo,+ large,+ onLarge,+ onVersions,+ onExport,+}: {+ entry: KineticEntry;+ onBack: () => void;+ onScene: (e: KineticEntry) => void;+ canUndo: boolean;+ canRedo: boolean;+ onUndo: () => void;+ onRedo: () => void;+ large: boolean;+ onLarge: (v: boolean) => void;+ onVersions: () => void;+ onExport: () => void;+}) {+ return (+ <div className="flex h-14 min-w-0 items-center gap-1 border-b bg-background px-2 sm:px-3" data-kinetic-bar>+ <button type="button" onClick={onBack} className="inline-flex h-11 min-w-11 shrink-0 items-center justify-center gap-1.5 rounded-full px-2.5 text-[13px] font-medium outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring">+ <ArrowLeft className="size-4" /> <span className="hidden sm:inline">All scenes</span>+ <span className="sr-only sm:hidden">All scenes</span>+ </button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button type="button" className="inline-flex h-11 min-w-11 shrink-0 items-center justify-center gap-1.5 rounded-full px-3 text-[13px] font-medium outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring xl:hidden" aria-label="Scenes">+ <LayoutGrid className="size-4" /> <span className="hidden md:inline">Scenes</span>+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-64">+ {KINETIC_SCENES.map((e) => (+ <DropdownMenuItem key={e.slug} onSelect={() => onScene(e)} className="min-h-11 gap-2">+ <Check className={cn("size-4", e.slug === entry.slug ? "opacity-100" : "opacity-0")} />+ {e.name}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ <h1 className="min-w-0 flex-1 truncate px-1 font-heading text-[18px] leading-tight sm:text-[20px]">{entry.name}</h1>+ <button type="button" onClick={onUndo} disabled={!canUndo} aria-label="Undo" className={iconButton}>+ <Undo2 className="size-4" />+ </button>+ <button type="button" onClick={onRedo} disabled={!canRedo} aria-label="Redo" className={iconButton}>+ <Redo2 className="size-4" />+ </button>+ <button type="button" onClick={() => onLarge(!large)} aria-pressed={large} aria-label="Large preview" className={cn(iconButton, "hidden lg:grid")}>+ {large ? <Shrink className="size-4" /> : <Expand className="size-4" />}+ </button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button type="button" aria-label="More" className={iconButton}>+ <MoreHorizontal className="size-4" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-56">+ <DropdownMenuLabel className="text-[12px]">{entry.name}</DropdownMenuLabel>+ <DropdownMenuSeparator />+ <DropdownMenuItem onSelect={onVersions} className="min-h-11">+ Versions+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={onExport} className="min-h-11">+ Export options+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}diff --git a/src/components/kinetic/editor.tsx b/src/components/kinetic/editor.tsxnew file mode 100644index 00000000..ac3376e1--- /dev/null+++ b/src/components/kinetic/editor.tsx@@ -0,0 +1,376 @@+"use client";++import { Loader2, Save, Settings2 } from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { measureText } from "@/components/ads/render";+import { PicturePicker } from "@/components/marketing/kinetic-template";+import { useBrands } from "@/components/marketing/hooks";+import { BrandRow, kitBrand, useStoredBrand } from "@/components/motion/brand-row";+import { SizeChips } from "@/components/motion/easy-chips";+import { shortenLine, TemplateFields } from "@/components/motion/fields";+import { useReducedMotion, useScene } from "@/components/motion/player";+import { CoverArt } from "@/components/template-cover";+import { useIsGuest, useIsOwner } from "@/lib/api";+import type { Generation } from "@/lib/catalog/types";+import { KINETIC_SCENES, normalizeKinetic, restingTime, templateOf, type KineticEntry } from "@/lib/motion/kinetic-catalog";+import { brandOf, clearTiming, docFiles, docFrom, docWords, easyValue, hasTiming, setBrand, setDuration, setEasy, setField, setProduct, setSize, type KineticDoc } from "@/lib/motion/kinetic-doc";+import { recipeKey, type Recipe } from "@/lib/motion/recipe";+import type { ScenePlan } from "@/lib/motion/scene";+import { exportSize, type SizePreset } from "@/lib/motion/sizes";+import { templateLengths, templateSizes, type TemplateBrand } from "@/lib/motion/template";+import { templateCover } from "@/lib/template-covers";+import { cn } from "@/lib/utils";+import { ClipControl } from "./clip-picker";+import { Choices, Segmented, SliderField } from "./controls";+import { readChoice, writeChoice } from "./draft";+import { EditorBar } from "./editor-bar";+import { ExportSheet, useMp4 } from "./export-sheet";+import { GroupSheet } from "./group-sheet";+import { jobLine, useKineticJobs, type JobKind } from "./jobs";+import { KineticPreview, Transport, useKineticInputs, useKineticPlan, usePreviewMode } from "./preview";+import { ProPanels } from "./pro-panels";+import { createTimeStore } from "./time-store";+import { Timeline } from "./timeline";+import type { KineticEditor } from "./use-editor";+import { recipeOfResult, VersionsSheet } from "./versions-sheet";++/**+ * The editor: the live preview with its transport, Easy (the template's own words and choices) or Pro (the real values+ * in four panels and a Timeline), and the Save bar. Phones stack it with the Save bar held at the foot; from 1024 px the+ * controls sit in a right-hand panel with their own scroll, and from 1280 px the scenes list sits on the left.+ */++type Mode = "easy" | "pro";++/** Whether the viewport is at least `px` wide (false on the server and first render). */+export function useMinWidth(px: number): boolean {+ const [on, setOn] = useState(false);+ useEffect(() => {+ const mq = window.matchMedia(`(min-width: ${px}px)`);+ const f = () => setOn(mq.matches);+ f();+ mq.addEventListener("change", f);+ return () => mq.removeEventListener("change", f);+ }, [px]);+ return on;+}++function OwnerBrand({ value, onChange }: { value: TemplateBrand; onChange: (b: TemplateBrand) => void }) {+ const kits = useBrands().data?.filter((k) => k.status !== "researching");+ const [kitId, setKitId] = useState<string | null>(null);+ return (+ <BrandRow+ value={value}+ onChange={onChange}+ kits={kits}+ kitId={kitId}+ onKit={(id) => {+ setKitId(id);+ const k = kits?.find((x) => x.id === id);+ if (k) onChange(kitBrand(k));+ }}+ />+ );+}++function SceneRail({ entry, onScene }: { entry: KineticEntry; onScene: (e: KineticEntry) => void }) {+ return (+ <nav aria-label="Scenes" className="min-h-0 overflow-y-auto border-r p-2">+ <ul className="space-y-1">+ {KINETIC_SCENES.map((e) => {+ const cover = templateCover("marketing", e.template);+ const on = e.slug === entry.slug;+ return (+ <li key={e.slug}>+ <button type="button" onClick={() => onScene(e)} aria-current={on ? "true" : undefined} className={cn("flex min-h-[68px] w-full min-w-0 items-center gap-3 rounded-xl p-1.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring", on ? "bg-accent" : "hover:bg-accent/60")}>+ <span className="relative block size-14 shrink-0 overflow-hidden rounded-lg bg-muted">{cover && <CoverArt cover={cover} sizes="56px" />}</span>+ <span className={cn("min-w-0 truncate text-[13px]", on ? "font-semibold" : "font-medium")}>{e.name}</span>+ </button>+ </li>+ );+ })}+ </ul>+ </nav>+ );+}++export function Editor({ editor, doc, entry, onBack, onScene, missing }: { editor: KineticEditor; doc: KineticDoc; entry: KineticEntry; onBack: () => void; onScene: (e: KineticEntry) => void; missing: ReadonlySet<string> }) {+ const r = doc.recipe;+ const t = templateOf(entry);+ const owner = useIsOwner();+ // A guest's Save always answers (with the sign-up card), even where this browser can't make the clip.+ const guest = useIsGuest();+ const [, setStored] = useStoredBrand();+ const inputs = useKineticInputs(r);+ const scene = useScene(r.scene);+ const plan = useKineticPlan(scene, r, inputs);+ const time = useMemo(() => createTimeStore(), []);+ const reduced = useReducedMotion();+ const [previewMode, setPreviewMode] = usePreviewMode();+ // The editor only ever renders in the browser (the studio waits for who is looking), so the choice reads at once.+ const [mode, setModeState] = useState<Mode>(() => readChoice("mode", ["easy", "pro"] as const, "easy"));+ const setMode = (m: Mode) => {+ setModeState(m);+ writeChoice("mode", m);+ };+ const jobs = useKineticJobs();+ const wide = useMinWidth(768);+ const desk = useMinWidth(1024);+ const side = wide ? "right" : "bottom";+ const [sheet, setSheet] = useState<"export" | "versions" | null>(null);+ const [group, setGroup] = useState<string | null>(null);+ const [large, setLarge] = useState(false);+ const px = exportSize(r.size);+ const previewBox = useRef<HTMLDivElement>(null);+ const timelineBox = useRef<HTMLDivElement>(null);+ const [timelineH, setTimelineH] = useState(0);+ const mp4 = useMp4(px.w - (px.w % 2), px.h - (px.h % 2), r.fps);++ // The preview starts playing once the scene is ready (never with reduced motion: the rest frame waits for Play).+ const started = useRef(false);+ useEffect(() => {+ if (!plan || started.current) return;+ started.current = true;+ if (!reduced) time.setPlaying(true);+ }, [plan, reduced, time]);++ // A save pauses the preview: its clip and the export's would both decode at once.+ const working = !!jobs.job;+ useEffect(() => {+ if (working) time.setPlaying(false);+ }, [working, time]);++ // Phones: retiming keeps the preview in view above its half-height sheet.+ useEffect(() => {+ if (!group || desk) return;+ const el = previewBox.current;+ if (el) window.scrollTo({ top: Math.max(0, el.getBoundingClientRect().top + window.scrollY - 64), behavior: reduced ? "auto" : "smooth" });+ }, [group, desk, reduced]);++ // The timing panel in the right-hand column closes with Escape, as the sheets do.+ useEffect(() => {+ if (!group || !desk || large) return;+ const onKey = (e: KeyboardEvent) => e.key === "Escape" && setGroup(null);+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [group, desk, large]);++ // Pro on desktop: the preview leaves room for the Timeline under it (never below 45% of the height).+ const timelineShown = desk && mode === "pro" && !!plan;+ useEffect(() => {+ const el = timelineBox.current;+ if (!timelineShown || !el) return setTimelineH(0);+ const ro = new ResizeObserver(() => setTimelineH(el.offsetHeight));+ ro.observe(el);+ return () => ro.disconnect();+ }, [timelineShown]);++ useEffect(() => {+ if (!large) return;+ const onKey = (e: KeyboardEvent) => e.key === "Escape" && setLarge(false);+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [large]);++ const planWith = useCallback(+ (rec: Recipe): ScenePlan | null => {+ if (!scene || !inputs.ready) return null;+ try {+ return scene.plan({ recipe: rec, measure: measureText, logo: inputs.logo, images: inputs.images, outlines: inputs.outlines, ...(inputs.clip.info && { clips: { clip: inputs.clip.info } }) });+ } catch {+ return null;+ }+ },+ [scene, inputs],+ );++ const fields = t.fields ?? [];+ const overflow = plan?.overflow ?? [];+ const brandOver = overflow.includes("brand");+ const overflowLine = overflow.length ? fields.filter((f) => overflow.includes(f.key)).map(shortenLine).concat(brandOver ? ["Shorten the brand name to fit"] : []).join(" · ") : null;+ const mp4Line = r.export.format === "mp4" && mp4 === false ? "This browser can't make MP4 here. Pick WebM in Export options." : null;++ // Versions: what was opened, saved or restored last (Restore asks first when the open state differs from it).+ const key = recipeKey(r);+ const [versionKey, setVersionKey] = useState(key);+ const words = docWords(doc, entry);+ const meta = (kind: JobKind, at?: number) => {+ const title = kind === "clip" ? `${entry.name} · ${words.first}` : kind === "frame" ? `Frame · ${entry.name} · ${(at ?? 0).toFixed(1)} s` : kind === "sheet" ? `Contact sheet · ${entry.name} · ${words.first}` : `Version · ${entry.name} · ${words.first}`;+ return { title: title.slice(0, 200), prompt: words.prompt, images: docFiles(r) };+ };+ const save = (kind: JobKind) => {+ if (!plan) return Promise.resolve(null);+ const at = kind === "frame" ? Math.min(plan.rest, time.get()) : undefined;+ return jobs.run(kind, r, inputs, meta(kind, at), { at }).then((g) => {+ if (g && kind === "version") setVersionKey(key);+ return g;+ });+ };+ const restore = (g: Generation) => {+ const n = normalizeKinetic(recipeOfResult(g));+ if (!n) return;+ editor.restore(docFrom(n.recipe));+ setVersionKey(recipeKey(n.recipe));+ setSheet(null);+ };++ const setBrandValue = (b: TemplateBrand) => {+ editor.apply((d) => setBrand(d, b), { gesture: true });+ if (!owner) setStored(b);+ };+ const easyGroups = t.easy ?? [];+ const sizes = templateSizes(t);+ const lengths = templateLengths(t);+ const busy = jobLine(jobs.job);+ const blocked = overflowLine ? "Shorten the words to fit, then save." : null;++ const saveBar = (+ <div className="flex min-w-0 items-center gap-2">+ <button+ type="button"+ onClick={() => (jobs.job?.kind === "clip" ? jobs.cancel() : void save("clip"))}+ disabled={!plan || !!blocked || (!!mp4Line && !guest) || (!!jobs.job && jobs.job.kind !== "clip")}+ data-kinetic-save="main"+ className="flex h-12 min-w-0 flex-1 items-center justify-center gap-2 rounded-full bg-primary px-4 text-[15px] font-medium text-primary-foreground shadow-soft outline-none transition-opacity hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50"+ >+ {jobs.job?.kind === "clip" ? <Loader2 className="size-4 animate-spin" /> : <Save className="size-4" />}+ <span className="truncate">{jobs.job?.kind === "clip" ? busy : jobs.job ? "Saving another one…" : jobs.saveLabel}</span>+ </button>+ <button type="button" onClick={() => setSheet("export")} aria-label="Export options" className="grid size-12 shrink-0 place-items-center rounded-full bg-secondary outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring">+ <Settings2 className="size-5" />+ </button>+ </div>+ );+ const saveNotes = (overflowLine || mp4Line) && (+ <p className="mt-1.5 text-[12px] text-muted-foreground" aria-live="polite">+ {overflowLine ?? mp4Line}+ </p>+ );++ const controls = (+ <div className="min-w-0 space-y-5">+ <Segmented+ label="Controls"+ hideLabel+ choices={[+ { id: "easy", label: "Easy" },+ { id: "pro", label: "Pro" },+ ]}+ value={mode}+ onChange={setMode}+ />+ <TemplateFields fields={fields} values={r.fields} onChange={(k, v) => editor.apply((d) => setField(d, entry, k, v), { gesture: true })} overflow={overflow} />+ {owner ? <OwnerBrand value={brandOf(doc)} onChange={setBrandValue} /> : <BrandRow value={brandOf(doc)} onChange={setBrandValue} />}+ {missing.has("logo") && <p className="-mt-3 text-[12px] text-destructive">Pick the logo again</p>}+ {brandOver && <p className="-mt-3 text-[12px] text-destructive">Shorten the brand name to fit</p>}+ {t.picture === "product" && (+ <div className="min-w-0">+ <PicturePicker value={r.media?.product} onChange={(url) => editor.apply((d) => setProduct(d, url))} owner={owner} />+ {missing.has("product") && <p className="mt-1 text-[12px] text-destructive">Pick the picture again</p>}+ </div>+ )}+ {entry.clip && <ClipControl doc={doc} editor={editor} time={time} clip={inputs.clip} side={side} pro={mode === "pro"} />}+ {missing.has("clip") && !r.layers?.video && <p className="-mt-3 text-[12px] text-destructive">Pick the clip again</p>}+ {mode === "easy" && easyGroups.map((g) => <Choices key={g.id} label={g.label} choices={g.choices} value={easyValue(doc, entry, g.id)} onChange={(c) => editor.apply((d) => setEasy(d, entry, g.id, c))} />)}+ {mode === "easy" && hasTiming(r) && (+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <span className="inline-flex h-8 items-center rounded-full bg-secondary px-3 text-[12px] font-medium">Has timing edits</span>+ <button type="button" onClick={() => editor.apply(clearTiming)} className="h-11 rounded-full px-3 text-[13px] font-medium underline-offset-4 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring">+ Clear timing edits+ </button>+ </div>+ )}+ <SizeChips sizes={sizes} value={(typeof r.size === "string" ? r.size : "custom") as SizePreset} onChange={(s) => editor.apply((d) => setSize(d, s))} />+ {lengths.max > lengths.min && <SliderField label="Length" unit="s" display={(v) => `${v} s`} value={r.duration} min={lengths.min} max={lengths.max} step={lengths.max - lengths.min <= 2 ? 0.5 : 1} onChange={(v) => editor.apply((d) => setDuration(d, v), { gesture: true })} onEnd={editor.end} />}+ {mode === "pro" && <ProPanels doc={doc} entry={entry} editor={editor} time={time} />}+ {mode === "pro" && plan && !desk && <Timeline plan={plan} doc={doc} time={time} editor={editor} onGroup={setGroup} />}+ </div>+ );++ const ratio = plan ? plan.design.w / plan.design.h : 9 / 16;+ const preview = (+ <KineticPreview+ plan={plan}+ recipe={r}+ inputs={inputs}+ time={time}+ mode={previewMode}+ label={`${entry.name} preview: ${words.prompt}`}+ hold={plan ? restingTime(plan, r) : undefined}+ className="mx-auto w-full"+ style={+ desk+ ? { maxWidth: `min(100%, calc(max(var(--content-h) * 0.45, var(--content-h) - 9.5rem - ${timelineShown && !large ? timelineH + 16 : 0}px) * ${ratio}))` }+ : { maxWidth: `min(100%, calc(${group ? 34 : 56}svh * ${ratio}))` }+ }+ />+ );+ const transport = plan ? <Transport time={time} duration={r.duration} fps={r.fps} rest={plan.rest} mode={previewMode} onMode={setPreviewMode} /> : <div className="h-11" />;++ return (+ <div className="flex min-w-0 flex-col lg:h-[var(--content-h)]" data-kinetic-editor={entry.slug} data-recipe-key={key}>+ <EditorBar+ entry={entry}+ onBack={onBack}+ onScene={onScene}+ canUndo={editor.canUndo}+ canRedo={editor.canRedo}+ onUndo={editor.undo}+ onRedo={editor.redo}+ large={large}+ onLarge={setLarge}+ onVersions={() => setSheet("versions")}+ onExport={() => setSheet("export")}+ />+ <div className={cn("min-w-0 lg:grid lg:min-h-0 lg:flex-1", large ? "lg:grid-cols-1" : "lg:grid-cols-[minmax(0,1fr)_380px] xl:grid-cols-[264px_minmax(0,1fr)_380px]")}>+ {!large && (+ <div className="hidden min-h-0 xl:flex xl:flex-col">+ <SceneRail entry={entry} onScene={onScene} />+ </div>+ )}+ <div className="min-w-0 px-4 pt-3 lg:min-h-0 lg:overflow-y-auto lg:px-6 lg:pt-5">+ <div className="mx-auto w-full max-w-[1100px] min-w-0" ref={previewBox}>+ {preview}+ <div className="mx-auto mt-1.5 w-full min-w-0" style={desk ? { maxWidth: "min(100%, 720px)" } : undefined}>+ {transport}+ </div>+ {desk && mode === "pro" && plan && (+ <div className="mt-4 min-w-0 pb-6" ref={timelineBox}>+ <Timeline plan={plan} doc={doc} time={time} editor={editor} onGroup={setGroup} />+ </div>+ )}+ </div>+ </div>+ {!large && desk && (+ <aside aria-label="Controls" className="hidden min-h-0 border-l lg:flex lg:flex-col">+ {group ? (+ <div className="min-h-0 flex-1 overflow-y-auto">+ <GroupSheet inline open groupId={group} onClose={() => setGroup(null)} doc={doc} editor={editor} side="right" planWith={planWith} />+ </div>+ ) : (+ <div className="min-h-0 flex-1 overflow-y-auto p-4">{controls}</div>+ )}+ <div className="border-t bg-background p-3">+ {saveBar}+ {saveNotes}+ </div>+ </aside>+ )}+ </div>+ {/* Phones: the controls under the preview, the Save bar held at the foot above the app's own bar. */}+ {!desk && (+ <>+ <div className="min-w-0 px-4 pt-4 pb-28 lg:hidden">{controls}</div>+ <div className="sticky bottom-chrome z-20 min-w-0 border-t bg-background/95 px-4 pt-2.5 pb-[max(0.625rem,env(safe-area-inset-bottom))] backdrop-blur lg:hidden" data-kinetic-savebar>+ {saveBar}+ {saveNotes}+ </div>+ </>+ )}++ <ExportSheet open={sheet === "export"} onClose={() => setSheet(null)} side={side} doc={doc} entry={entry} editor={editor} jobs={jobs} blocked={blocked} mp4={mp4} onSave={(k) => void save(k)} />+ <VersionsSheet open={sheet === "versions"} onClose={() => setSheet(null)} side={side} jobs={jobs} onSaveVersion={() => save("version")} onRestore={restore} dirty={key !== versionKey} />+ <GroupSheet open={!!group && (!desk || large)} onClose={() => setGroup(null)} groupId={group} doc={doc} editor={editor} side={side} planWith={planWith} />+ </div>+ );+}diff --git a/src/components/kinetic/export-sheet.tsx b/src/components/kinetic/export-sheet.tsxnew file mode 100644index 00000000..8b529833--- /dev/null+++ b/src/components/kinetic/export-sheet.tsx@@ -0,0 +1,212 @@+"use client";++import { Check, Clapperboard, Grid3x3, ImageIcon, Loader2, X } from "lucide-react";+import Link from "next/link";+import { useEffect, useRef, useState } from "react";+import { canMakeMp4 } from "@/components/motion/render";+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";+import { templateLengths, templateSizes } from "@/lib/motion/template";+import { setDuration, setExport, setFps, setSize, type KineticDoc } from "@/lib/motion/kinetic-doc";+import { templateOf, type KineticEntry } from "@/lib/motion/kinetic-catalog";+import { customSizeProblem, exportSize, KINETIC_FPS, SIZE_LABELS, type SizePreset } from "@/lib/motion/sizes";+import { cn } from "@/lib/utils";+import { Choices, iconButton, Segmented, sheetClass, SliderField } from "./controls";+import { jobLine, type JobKind, type KineticJobs } from "./jobs";+import type { KineticEditor } from "./use-editor";++/**+ * Export options: format, size (the scene's sizes or a custom one), frame rate, length, motion blur and quality, with+ * the three outputs (the clip, a frame at the playhead, a 9-frame contact sheet). Nothing here changes the preview's+ * own quality; MP4 is never swapped for WebM without saying so.+ */+++export const KIND_NAMES: Record<JobKind, string> = { clip: "Clip", frame: "Frame", sheet: "Contact sheet", version: "Version" };++/** Whether this browser can make an MP4 at the recipe's size and rate (null while it checks). */+export function useMp4(w: number, h: number, fps: number): boolean | null {+ const [ok, setOk] = useState<{ key: string; ok: boolean } | null>(null);+ const key = `${w}x${h}@${fps}`;+ useEffect(() => {+ let live = true;+ canMakeMp4(w, h, fps)+ .then((v) => live && setOk({ key, ok: v }))+ .catch(() => live && setOk({ key, ok: false }));+ return () => {+ live = false;+ };+ }, [w, h, fps, key]);+ return ok?.key === key ? ok.ok : null;+}++function CustomSize({ value, onChange }: { value: { w: number; h: number }; onChange: (s: { w: number; h: number }) => void }) {+ const [w, setW] = useState(String(value.w));+ const [h, setH] = useState(String(value.h));+ const problem = customSizeProblem(Number(w), Number(h));+ const commit = () => {+ if (!customSizeProblem(Number(w), Number(h))) onChange({ w: Number(w), h: Number(h) });+ };+ const box = "h-11 w-full min-w-0 rounded-xl border bg-background px-3 text-[14px] tabular-nums outline-none focus-visible:border-primary focus-visible:ring-2 focus-visible:ring-ring";+ return (+ <div className="min-w-0">+ <div className="grid grid-cols-[1fr_auto_1fr] items-center gap-2">+ <input aria-label="Width in pixels" inputMode="numeric" value={w} onChange={(e) => setW(e.target.value)} onBlur={commit} onKeyDown={(e) => e.key === "Enter" && commit()} className={box} />+ <span className="text-[13px] text-muted-foreground" aria-hidden>+ ×+ </span>+ <input aria-label="Height in pixels" inputMode="numeric" value={h} onChange={(e) => setH(e.target.value)} onBlur={commit} onKeyDown={(e) => e.key === "Enter" && commit()} className={box} />+ </div>+ <p className={cn("mt-1 text-[12px]", problem ? "text-destructive" : "text-muted-foreground")}>{problem ?? "Even numbers, 256 to 2160 px a side."}</p>+ </div>+ );+}++export function ExportSheet({+ open,+ onClose,+ side,+ doc,+ entry,+ editor,+ jobs,+ blocked,+ mp4,+ onSave,+}: {+ open: boolean;+ onClose: () => void;+ side: "bottom" | "right";+ doc: KineticDoc;+ entry: KineticEntry;+ editor: Pick<KineticEditor, "apply" | "end">;+ jobs: KineticJobs;+ /** Why nothing can save yet (words that don't fit, MP4 that can't be made here), or null. */+ blocked: string | null;+ /** Whether this browser makes an MP4 at this size (null while it checks). */+ mp4: boolean | null;+ onSave: (kind: JobKind) => void;+}) {+ const r = doc.recipe;+ const t = templateOf(entry);+ const sizes = templateSizes(t);+ const lengths = templateLengths(t);+ const px = exportSize(r.size);+ const custom = typeof r.size !== "string";+ const busy = jobLine(jobs.job);+ const title = useRef<HTMLHeadingElement>(null);+ const out = (kind: JobKind, label: string, Icon: typeof Clapperboard) => {+ const mine = jobs.job?.kind === kind;+ return (+ <button+ type="button"+ onClick={() => onSave(kind)}+ disabled={!!blocked || (kind === "clip" && r.export.format === "mp4" && mp4 === false && !jobs.guest) || (!!jobs.job && !mine)}+ data-kinetic-save={kind}+ className={cn("flex h-12 w-full min-w-0 items-center gap-2 rounded-xl px-4 text-[14px] font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50", kind === "clip" ? "bg-primary text-primary-foreground hover:opacity-90" : "bg-secondary hover:bg-accent")}+ >+ {mine ? <Loader2 className="size-4 animate-spin" /> : <Icon className="size-4" />}+ <span className="truncate">{mine ? busy : jobs.job ? "Saving another one…" : label}</span>+ </button>+ );+ };+ return (+ <Sheet open={open} onOpenChange={(v) => !v && onClose()}>+ <SheetContent+ side={side}+ showCloseButton={false}+ className={sheetClass}+ data-kinetic-sheet="export"+ onOpenAutoFocus={(e) => {+ // The title takes focus (a heavy ring on Close after a mouse open reads as a mistake).+ e.preventDefault();+ title.current?.focus();+ }}+ >+ <SheetHeader className="flex-row items-start gap-2 pb-3">+ <div className="min-w-0 flex-1">+ <SheetTitle ref={title} tabIndex={-1} className="outline-none">+ Export options+ </SheetTitle>+ <SheetDescription className="text-[13px]">+ How the clip is made. Saved results go to {jobs.saveLabel === "Save to Library" ? "your Library" : "your runs"}, where they download.+ {jobs.account && " You can save about 30 clips or 60 pictures an hour."}+ </SheetDescription>+ </div>+ <button type="button" onClick={onClose} aria-label="Close" className={iconButton}>+ <X className="size-4" />+ </button>+ </SheetHeader>+ <div className="min-w-0 space-y-4 px-4 pb-2">+ <div className="min-w-0">+ <Segmented+ label="Format"+ choices={[+ { id: "mp4", label: "MP4" },+ { id: "webm", label: "WebM" },+ ]}+ value={r.export.format}+ onChange={(f) => (f === "mp4" && mp4 === false ? undefined : editor.apply((d) => setExport(d, { format: f })))}+ />+ {mp4 === false && <p className="mt-1 text-[12px] text-muted-foreground">This browser can't make MP4 here. WebM works.</p>}+ </div>+ <div className="min-w-0 space-y-2">+ <Choices+ label="Size"+ choices={[...sizes.map((s) => ({ id: s as string, label: SIZE_LABELS[s] })), { id: "custom", label: "Custom" }]}+ value={custom ? "custom" : (r.size as string)}+ onChange={(id) => editor.apply((d) => setSize(d, id === "custom" ? { w: px.w - (px.w % 2), h: px.h - (px.h % 2) } : (id as SizePreset)))}+ />+ {custom && <CustomSize key={`${px.w}x${px.h}`} value={r.size as { w: number; h: number }} onChange={(s) => editor.apply((d) => setSize(d, s))} />}+ </div>+ <Choices label="Frame rate" choices={KINETIC_FPS.map((f) => ({ id: String(f), label: `${f} fps` }))} value={String(r.fps)} onChange={(f) => editor.apply((d) => setFps(d, Number(f) as typeof r.fps))} note={r.fps === 60 ? "twice the frames" : undefined} />+ {lengths.max > lengths.min && <SliderField label="Length" unit="s" display={(v) => `${v} s`} value={r.duration} min={lengths.min} max={lengths.max} step={lengths.max - lengths.min <= 2 ? 0.5 : 1} onChange={(v) => editor.apply((d) => setDuration(d, v), { gesture: true })} onEnd={editor.end} />}+ <SliderField label="Motion blur samples" display={(v) => (v <= 1 ? "Off" : String(v))} value={r.export.blurSamples} min={1} max={32} step={1} onChange={(v) => editor.apply((d) => setExport(d, { blurSamples: v }), { gesture: true })} onEnd={editor.end} />+ <SliderField label="Shutter" unit="°" display={(v) => `${Math.round(v)}°`} value={r.export.shutter} min={0} max={360} step={15} onChange={(v) => editor.apply((d) => setExport(d, { shutter: v }), { gesture: true })} onEnd={editor.end} disabled={r.export.blurSamples <= 1} />+ <Segmented+ label="Quality"+ choices={[+ { id: "standard", label: "Standard" },+ { id: "high", label: "High" },+ ]}+ value={r.export.quality ?? "standard"}+ onChange={(q) => editor.apply((d) => setExport(d, { quality: q === "high" ? "high" : undefined }))}+ />+ <p className="text-[12px] text-muted-foreground tabular-nums">+ {px.w - (px.w % 2)} × {px.h - (px.h % 2)} · {r.fps} fps · {r.duration} s+ </p>+ </div>+ <div className="sticky bottom-0 min-w-0 space-y-2 border-t bg-popover px-4 pt-3">+ {blocked && <p className="text-[12px] text-destructive">{blocked}</p>}+ {out("clip", "Save clip", Clapperboard)}+ <div className="grid grid-cols-1 gap-2 min-[420px]:grid-cols-2">+ {out("frame", "Save frame", ImageIcon)}+ {out("sheet", "Save contact sheet", Grid3x3)}+ </div>+ {jobs.job && (+ <button type="button" onClick={jobs.cancel} className="h-11 w-full rounded-full text-[13px] font-medium text-muted-foreground outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring">+ Stop+ </button>+ )}+ {jobs.saved.length > 0 && (+ <div className="min-w-0 pb-1" data-kinetic-saved>+ <p className="mb-1 text-[12px] font-medium text-muted-foreground">Saved this visit</p>+ <ul className="space-y-1">+ {jobs.saved.map((s) => (+ <li key={s.id} className="flex min-h-11 min-w-0 items-center gap-2 text-[13px]">+ <Check className="size-4 shrink-0 text-primary" aria-hidden />+ <span className="min-w-0 flex-1 truncate">+ {KIND_NAMES[s.kind]} · {s.title}+ </span>+ <Link href="/library" prefetch={false} className="inline-flex h-11 shrink-0 items-center rounded-full px-3 font-medium underline-offset-4 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring">+ Open+ </Link>+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ </SheetContent>+ </Sheet>+ );+}diff --git a/src/components/kinetic/group-sheet.tsx b/src/components/kinetic/group-sheet.tsxnew file mode 100644index 00000000..bfb1f39c--- /dev/null+++ b/src/components/kinetic/group-sheet.tsx@@ -0,0 +1,195 @@+"use client";++import { X } from "lucide-react";+import { useMemo } from "react";+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";+import { clampRate, groupsOf, IDENTITY_KEYS, rateLimits, shapeKeys, shotWindows, SHAPES, type WarpKeys } from "@/lib/motion/edit";+import { groupDefsFor } from "@/lib/motion/kinetic-groups";+import { setPro, type KineticDoc } from "@/lib/motion/kinetic-doc";+import type { GroupTiming, Recipe } from "@/lib/motion/recipe";+import type { ScenePlan } from "@/lib/motion/scene";+import { cn } from "@/lib/utils";+import { iconButton, sheetClass, SliderField } from "./controls";+import { CurveGraph } from "./curve-graph";+import type { KineticEditor } from "./use-editor";++/**+ * One motion group's timing: its curve (a retiming of its own clock, not a second easing) and its rate. The rate's+ * range is held so the group stays inside its shot and a second before the last frame. Opening or closing the sheet+ * changes nothing; every edit is one undo step. The preview stays in view while it is open: from 1024 px it sits in the+ * right-hand panel (`inline`), and on phones it is a half-height sheet with no overlay under a smaller preview.+ */++/** The recipe without any group timing: the scene's own clock, which the rate limits are measured on. */+export const untimed = (r: Recipe): Recipe => {+ const out = { ...r };+ delete out.groups;+ return out;+};++/** The zoom of a plan's camera at 60 times (the Camera group's sampled line). */+function sampledZoom(plan: ScenePlan, a: number, b: number): number[] {+ const out: number[] = [];+ for (let i = 0; i < 60; i++) {+ const list = plan.evaluate(a + ((b - a) * i) / 59);+ const cam = list.nodes.find((n) => n.type === "group" && n.id === "camera");+ const m = cam && cam.type === "group" ? cam.transform : undefined;+ out.push(m ? Math.hypot(m[0], m[1]) : 1);+ }+ return out;+}++export function GroupSheet({+ open,+ onClose,+ groupId,+ doc,+ editor,+ side,+ planWith,+ inline,+}: {+ open: boolean;+ onClose: () => void;+ groupId: string | null;+ doc: KineticDoc;+ editor: Pick<KineticEditor, "apply" | "end">;+ side: "bottom" | "right";+ planWith: (r: Recipe) => ScenePlan | null;+ inline?: boolean;+}) {+ const r = doc.recipe;+ const untimedKey = JSON.stringify(untimed(r));+ // eslint-disable-next-line react-hooks/exhaustive-deps+ const base = useMemo(() => (open ? planWith(untimed(r)) : null), [open, untimedKey, planWith]);+ const info = useMemo(() => {+ if (!base || !groupId) return null;+ const windows = shotWindows(base);+ const g = groupsOf(groupDefsFor(r.scene), base.timeline.events, windows).find((x) => x.id === groupId);+ if (!g) return null;+ const limits = rateLimits(g, windows, base.rest);+ const [a, b] = windows[g.window] ?? [0, base.rest];+ return {+ g,+ limits,+ under: g.camera ? sampledZoom(base, a, b) : undefined,+ shots: windows.length,+ };+ }, [base, groupId, r.scene]);+ const timing: GroupTiming = (groupId && r.groups?.[groupId]) || {+ keys: IDENTITY_KEYS,+ rate: 1,+ };+ const setTiming = (next: Partial<GroupTiming>, gesture = false) => {+ if (!groupId) return;+ editor.apply(+ (d) =>+ setPro(d, (rec) => ({+ ...rec,+ groups: {+ ...(rec.groups ?? {}),+ [groupId]: {+ ...timing,+ ...next,+ keys: (next.keys ?? timing.keys).map((k) => [k[0], k[1]] as [number, number]),+ },+ },+ })),+ { gesture },+ );+ };+ const atLimit = info && info.limits.min > 0.5 && timing.rate <= info.limits.min + 1e-9;+ const name = info?.g.label ?? "Timing";++ const closeButton = (+ <button type="button" onClick={onClose} aria-label="Close" className={iconButton}>+ <X className="size-4" />+ </button>+ );+ const controls = info && (+ <div className="min-w-0 space-y-4 px-4 pb-4">+ <CurveGraph+ keys={timing.keys as WarpKeys}+ onChange={(keys) => setTiming({ keys })}+ label={`${name} timing curve`}+ under={info.under}+ underLabel={info.g.camera ? "Sampled from the scene's camera (dashed)" : undefined}+ />+ <div className="flex min-w-0 flex-wrap gap-1.5" role="group" aria-label="Suggested shapes">+ {SHAPES.map((s) => (+ <button+ key={s.id}+ type="button"+ onClick={() => setTiming({ keys: shapeKeys(s.id) })}+ className="h-11 rounded-full bg-secondary px-3.5 text-[13px] font-medium outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"+ >+ {s.label}+ </button>+ ))}+ </div>+ <SliderField+ label="Speed"+ display={(v) => `${v.toFixed(2)}x`}+ value={timing.rate}+ min={info.limits.min}+ max={info.limits.max}+ step={0.01}+ disabled={info.limits.min >= info.limits.max}+ onChange={(v) => setTiming({ rate: clampRate(v, info.limits) }, true)}+ onEnd={editor.end}+ note={atLimit ? "As slow as it can go here" : info.g.camera ? "The camera can run quicker, never slower." : undefined}+ />+ <button+ type="button"+ onClick={() => setTiming({ keys: IDENTITY_KEYS, rate: 1 })}+ className="h-11 w-full rounded-full border text-[13px] font-medium outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"+ >+ Reset timing+ </button>+ </div>+ );++ if (inline) {+ if (!open) return null;+ return (+ <section aria-labelledby="kinetic-group-title" className="min-w-0" data-kinetic-sheet="group">+ <div className="flex items-start gap-2 px-4 pt-3 pb-3">+ <div className="min-w-0 flex-1">+ <h2 id="kinetic-group-title" className="text-[16px] font-semibold">+ {name}+ </h2>+ <p className="mt-0.5 text-[13px] text-muted-foreground">+ {info?.g.camera ? "Sampled from the scene's camera. The camera still comes to rest on the last frame." : "Retimes this part's own clock. Cuts, words and length stay as they are."}+ </p>+ </div>+ {closeButton}+ </div>+ {controls}+ </section>+ );+ }++ return (+ // No overlay and no focus trap: the preview above stays live while the timing changes (Escape or Close shut it).+ <Sheet open={open} onOpenChange={(v) => !v && onClose()} modal={false}>+ <SheetContent+ side={side}+ showCloseButton={false}+ className={cn(sheetClass, "max-h-[50svh] shadow-[0_-8px_30px_rgb(0_0_0/0.18)]")}+ data-kinetic-sheet="group"+ onInteractOutside={(e) => e.preventDefault()}+ >+ <SheetHeader className="flex-row items-start gap-2 pb-3">+ <div className="min-w-0 flex-1">+ <SheetTitle>{name}</SheetTitle>+ <SheetDescription className="text-[13px]">+ {info?.g.camera ? "Sampled from the scene's camera. The camera still comes to rest on the last frame." : "Retimes this part's own clock. Cuts, words and length stay as they are."}+ </SheetDescription>+ </div>+ {closeButton}+ </SheetHeader>+ {controls}+ </SheetContent>+ </Sheet>+ );+}diff --git a/src/components/kinetic/history.ts b/src/components/kinetic/history.tsnew file mode 100644index 00000000..b4453a27--- /dev/null+++ b/src/components/kinetic/history.ts@@ -0,0 +1,49 @@+/**+ * Kinetic's undo and redo for one visit (pure): a stack of documents, at most HISTORY_MAX steps. A drag or a typed+ * number is one gesture: its first change opens a step and the rest replace it, until the gesture settles (on release,+ * or 400 ms after the last keystroke). A change that leaves the recipe as it was adds no step.+ */++import { stableJson } from "@/lib/motion/recipe";++export const HISTORY_MAX = 100;+/** A typing gesture settles this long after the last keystroke. */+export const SETTLE_MS = 400;++export interface History<T> {+ past: T[];+ present: T;+ future: T[];+ /** A gesture is open: its next change replaces the present instead of adding a step. */+ open: boolean;+}++export const startHistory = <T>(present: T): History<T> => ({ past: [], present, future: [], open: false });++const same = (a: unknown, b: unknown) => a === b || stableJson(a) === stableJson(b);++/** A change: a new step, or (inside an open gesture) the same step updated. */+export function change<T>(h: History<T>, next: T, o: { gesture?: boolean } = {}): History<T> {+ if (same(next, h.present)) return o.gesture ? h : { ...h, open: false };+ if (h.open && o.gesture) return { ...h, present: next, future: [] };+ return { past: [...h.past, h.present].slice(-HISTORY_MAX), present: next, future: [], open: !!o.gesture };+}++/** The open gesture is done: the next change is a step of its own. */+export const settle = <T>(h: History<T>): History<T> => (h.open ? { ...h, open: false } : h);++export function undo<T>(h: History<T>): History<T> {+ if (!h.past.length) return { ...h, open: false };+ return { past: h.past.slice(0, -1), present: h.past[h.past.length - 1], future: [h.present, ...h.future], open: false };+}++export function redo<T>(h: History<T>): History<T> {+ if (!h.future.length) return { ...h, open: false };+ return { past: [...h.past, h.present].slice(-HISTORY_MAX), present: h.future[0], future: h.future.slice(1), open: false };+}++/** A restored version: the current state goes on the stack, so Undo brings it back. */+export const restore = <T>(h: History<T>, version: T): History<T> => change(settle(h), version);++export const canUndo = (h: History<unknown>) => h.past.length > 0;+export const canRedo = (h: History<unknown>) => h.future.length > 0;diff --git a/src/components/kinetic/jobs.ts b/src/components/kinetic/jobs.tsnew file mode 100644index 00000000..99b8ab4e--- /dev/null+++ b/src/components/kinetic/jobs.ts@@ -0,0 +1,163 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";+import { useRouter } from "next/navigation";+import { useCallback, useRef, useState } from "react";+import { toast } from "sonner";+import { measureText } from "@/components/ads/render";+import { loadClip } from "@/components/motion/clip-source";+import { fontsReady } from "@/components/motion/fonts";+import { loadMotionInputs } from "@/components/motion/inputs";+import { renderClip, renderFrame, renderRest, renderSheet, type RenderOptions } from "@/components/motion/render";+import { saveMotionPicture, saveMotionResult, type SaveMeta } from "@/components/motion/save";+import { askToSignUp, useIsGuest, useIsOwner } from "@/lib/api";+import type { Generation } from "@/lib/catalog/types";+import { videoNodeOf } from "@/lib/motion/display";+import { recipeKey, type Recipe } from "@/lib/motion/recipe";+import { loadScene } from "@/lib/motion/registry";+import { toastError } from "@/lib/refusals";+import type { KineticInputs } from "./preview";++/**+ * Kinetic's outputs, one render at a time: a clip, a frame, a contact sheet or a version. A guest is asked to sign up+ * before anything renders. Each output is uploaded and recorded as a result (save.ts: the owner's Library, an account's+ * own runs), where it downloads; nothing is handed to the browser as a download here.+ */++export type JobKind = "clip" | "frame" | "sheet" | "version";++export const JOB_FEATURE: Record<JobKind, string> = { clip: "kinetic", frame: "kinetic-frame", sheet: "kinetic-sheet", version: "kinetic-version" };++export interface JobState {+ kind: JobKind;+ done: number;+ total: number;+ saving: boolean;+}++export interface SavedItem {+ id: string;+ kind: JobKind;+ title: string;+}++/** The render options for a recipe: the brand's fonts (strict), its pictures, and its clip on a video of its own (exact seeks). */+async function optionsFor(recipe: Recipe, inputs: KineticInputs, signal: AbortSignal, onProgress?: (d: number, n: number) => void): Promise<{ opts: RenderOptions; dispose: () => void }> {+ await fontsReady([recipe.brand.fonts.heading, recipe.brand.fonts.body], { strict: true, text: [...Object.values(recipe.fields), recipe.brand.name].join(" ") });+ const src = recipe.layers?.video?.src;+ const clip = src ? await loadClip(src, { signal }) : null;+ const sources = clip ? { ...inputs.sources, clips: new Map([["clip", clip.el as CanvasImageSource]]) } : inputs.sources;+ const opts: RenderOptions = {+ sources,+ logo: inputs.logo,+ images: inputs.images,+ outlines: inputs.outlines,+ measure: measureText,+ signal,+ formats: [recipe.export.format],+ onProgress: (d, n) => onProgress?.(d, n),+ ...(clip && {+ clips: { clip: clip.info },+ prepare: async (list) => {+ const v = videoNodeOf(list);+ if (v) await clip.seek(v.time);+ },+ }),+ };+ return { opts, dispose: () => clip?.dispose() };+}++export function useKineticJobs() {+ const guest = useIsGuest();+ const owner = useIsOwner();+ const qc = useQueryClient();+ const router = useRouter();+ const [job, setJob] = useState<JobState | null>(null);+ const [saved, setSaved] = useState<SavedItem[]>([]);+ const done = useRef(new Map<string, string>());+ const abort = useRef<AbortController | null>(null);++ const run = useCallback(+ async (kind: JobKind, recipe: Recipe, inputs: KineticInputs, meta: Omit<SaveMeta, "recipe" | "feature">, o: { at?: number } = {}): Promise<Generation | null> => {+ if (guest) {+ askToSignUp("upload");+ return null;+ }+ if (abort.current) return null;+ const key = `${kind}|${recipeKey(recipe)}|${o.at ?? ""}`;+ const where = owner ? "Saved to your Library" : "Saved to your runs";+ const openLibrary = { label: "Open", onClick: () => router.push("/library") };+ if (done.current.has(key)) {+ toast(owner ? "Already saved to your Library" : "Already saved to your runs", { action: openLibrary });+ return null;+ }+ const ctl = new AbortController();+ abort.current = ctl;+ let dispose = () => {};+ try {+ setJob({ kind, done: 0, total: 1, saving: false });+ const progress = (d: number, n: number) => setJob({ kind, done: d, total: n, saving: false });+ const scene = await loadScene(recipe.scene);+ const made = await optionsFor(recipe, inputs, ctl.signal, progress);+ dispose = made.dispose;+ const full: SaveMeta = { ...meta, recipe, feature: JOB_FEATURE[kind] };+ let g: Generation;+ if (kind === "clip") {+ const clip = await renderClip(scene, recipe, made.opts);+ if (ctl.signal.aborted) throw new DOMException("Stopped", "AbortError");+ setJob({ kind, done: 1, total: 1, saving: true });+ g = await saveMotionResult({ blob: clip.blob, type: clip.type, poster: clip.poster }, full);+ } else {+ const pic = kind === "frame" ? await renderFrame(scene, recipe, o.at ?? 0, made.opts) : kind === "sheet" ? await renderSheet(scene, recipe, made.opts) : await renderRest(scene, recipe, made.opts);+ if (ctl.signal.aborted) throw new DOMException("Stopped", "AbortError");+ setJob({ kind, done: 1, total: 1, saving: true });+ g = await saveMotionPicture(pic.blob, full);+ }+ done.current.set(key, g.id);+ setSaved((s) => [{ id: g.id, kind, title: meta.title }, ...s].slice(0, 20));+ void qc.invalidateQueries({ queryKey: ["generations"] });+ toast.success(where, { action: openLibrary });+ return g;+ } catch (e) {+ if ((e as Error).name !== "AbortError") toastError(e, "Couldn't save it. Try again.");+ return null;+ } finally {+ dispose();+ if (abort.current === ctl) abort.current = null;+ setJob(null);+ }+ },+ [guest, owner, qc, router],+ );++ const cancel = useCallback(() => abort.current?.abort(), []);+ // An account (not the owner, not a guest): its saves count toward its hourly limits, which the sheet says.+ return { run, cancel, job, saved, saveLabel: owner ? "Save to Library" : "Save to your runs", account: !owner && !guest, guest };+}++export type KineticJobs = ReturnType<typeof useKineticJobs>;++/** "Rendering 42 of 75", "Saving…", or null. */+export function jobLine(j: JobState | null): string | null {+ if (!j) return null;+ if (j.saving) return "Saving…";+ return `Rendering ${j.done} of ${j.total}`;+}++/**+ * A recipe's clip rendered with its own inputs loaded here (the Canvas node renders a row this way): its pictures, its+ * fonts and its clip. MP4 where the browser makes one, else WebM.+ */+export async function renderKineticClip(recipe: Recipe, o: { signal?: AbortSignal; onProgress?: (d: number, n: number) => void } = {}) {+ const loaded = await loadMotionInputs({ logo: recipe.brand.logo, product: recipe.media?.product });+ const inputs = { ...loaded, ready: true, version: 1, clip: { source: null, info: null, failed: false } } as KineticInputs;+ const ctl = new AbortController();+ o.signal?.addEventListener("abort", () => ctl.abort());+ const scene = await loadScene(recipe.scene);+ const made = await optionsFor(recipe, inputs, ctl.signal, o.onProgress);+ try {+ return await renderClip(scene, recipe, { ...made.opts, formats: ["mp4", "webm"] });+ } finally {+ made.dispose();+ }+}diff --git a/src/components/kinetic/kinetic-studio.tsx b/src/components/kinetic/kinetic-studio.tsxnew file mode 100644index 00000000..9fa2bfaf--- /dev/null+++ b/src/components/kinetic/kinetic-studio.tsx@@ -0,0 +1,186 @@+"use client";++import { useRouter, useSearchParams } from "next/navigation";+import { useCallback, useEffect, useRef, useState } from "react";+import { toast } from "sonner";+import { useViewer } from "@/lib/api";+import type { Generation } from "@/lib/catalog/types";+import { entryBySlug, entryForRecipe, exampleRecipe, kineticHref, normalizeKinetic, startRecipe, type KineticEntry, type KineticExample } from "@/lib/motion/kinetic-catalog";+import { brandOf, docFiles, docFrom, setBrand, setClip, setProduct, switchScene, type KineticDoc } from "@/lib/motion/kinetic-doc";+import { END_CARD_VARIANTS, type EndCardVariant } from "@/lib/motion/scenes/end-card/shared";+import { readDraft, writeDraft } from "./draft";+import { Editor } from "./editor";+import { ScenePicker } from "./scene-picker";+import { useKineticEditor } from "./use-editor";+import { recipeOfResult } from "./versions-sheet";++/**+ * Fuobe Kinetic Motion's page (/kinetic): the scene picker, or the editor on one scene. The address names what is open+ * (`scene`, the end card's `style`, or a saved result to open with `from`); a change of scene replaces it, so tweaks never+ * add history entries. The open recipe is kept as a draft in this browser, per viewer and scene.+ */++const styleOf = (v: string | null): EndCardVariant | null => (v && (END_CARD_VARIANTS as readonly string[]).includes(v) ? (v as EndCardVariant) : null);++/** A short, stable stand-in for who is looking (drafts are kept per viewer). */+function viewerKey(v: { owner: boolean; signedIn: boolean; account?: { email: string } } | undefined): string | null {+ if (!v) return null;+ if (v.owner) return "owner";+ if (!v.account) return "guest";+ let h = 5381;+ for (const c of v.account.email) h = ((h * 33) ^ c.charCodeAt(0)) >>> 0;+ return `a${h.toString(36)}`;+}++/** The style a recipe plays, for the address (end cards only). */+const recipeStyle = (d: KineticDoc) => (d.recipe.scene.startsWith("end-card/") ? d.recipe.scene.split("/")[1] : null);++/** The person's files a draft names that are gone now (404), dropped from it. */+async function dropGone(d: KineticDoc): Promise<{ doc: KineticDoc; missing: Set<string> }> {+ const missing = new Set<string>();+ const urls = [...docFiles(d.recipe), ...(d.recipe.layers?.video ? [d.recipe.layers.video.src] : [])];+ const gone = new Set<string>();+ await Promise.all(+ urls.map(async (u) => {+ try {+ const res = await fetch(u, { method: "HEAD" });+ if (res.status === 404) gone.add(u);+ } catch {}+ }),+ );+ let doc = d;+ if (doc.recipe.brand.logo && gone.has(doc.recipe.brand.logo)) {+ doc = setBrand(doc, { ...brandOf(doc), logo: null });+ missing.add("logo");+ }+ if (doc.recipe.media?.product && gone.has(doc.recipe.media.product)) {+ doc = setProduct(doc, null);+ missing.add("product");+ }+ if (doc.recipe.layers?.video && gone.has(doc.recipe.layers.video.src)) {+ doc = setClip(doc, null);+ missing.add("clip");+ }+ return { doc, missing };+}++export function KineticStudio() {+ const params = useSearchParams();+ const router = useRouter();+ const viewer = useViewer();+ const who = viewer.isError ? "guest" : viewerKey(viewer.data);+ const editor = useKineticEditor();+ const [view, setView] = useState<"loading" | "picker" | "editor">("loading");+ const [missing, setMissing] = useState<ReadonlySet<string>>(new Set());+ const booted = useRef(false);++ /** Opens a document in the editor (from a draft when this viewer has one for the scene and `fresh` isn't asked). */+ const openDoc = useCallback(+ async (entry: KineticEntry, o: { style?: EndCardVariant | null; fresh?: boolean; example?: KineticExample } = {}) => {+ const draft = !o.fresh && who ? readDraft(who, entry.slug) : null;+ let doc = docFrom(o.example ? exampleRecipe(o.example) : startRecipe(entry, { style: o.style }));+ let gone = new Set<string>();+ if (draft) {+ const n = normalizeKinetic(draft.recipe);+ if (n && n.entry.slug === entry.slug) {+ const checked = await dropGone({ recipe: n.recipe, logo: draft.logo });+ doc = checked.doc;+ gone = checked.missing;+ }+ }+ setMissing(gone);+ editor.open(doc);+ setView("editor");+ },+ [who, editor],+ );++ // The first open: a saved result (`from`), a scene (`scene`, `style`), or the picker.+ useEffect(() => {+ if (booted.current || !who) return;+ booted.current = true;+ const from = params.get("from");+ const entry = entryBySlug(params.get("scene"));+ void (async () => {+ if (from) {+ if (who === "guest") {+ // Nothing of a guest's to open: the picker, with no message.+ setView("picker");+ router.replace("/kinetic", { scroll: false });+ return;+ }+ try {+ const res = await fetch(`/api/generations/${encodeURIComponent(from)}`);+ const g = res.ok ? ((await res.json()) as Generation) : null;+ const n = g && g.modelId === "local-motion" ? normalizeKinetic(recipeOfResult(g)) : null;+ if (!n) throw new Error("gone");+ editor.open(docFrom(n.recipe));+ setView("editor");+ } catch {+ toast("We can't open that one.");+ setView("picker");+ router.replace("/kinetic", { scroll: false });+ }+ return;+ }+ if (entry) await openDoc(entry, { style: styleOf(params.get("style")) });+ // A tile picked while the page was still finding out who is looking has opened the editor already.+ else setView((v) => (v === "loading" ? "picker" : v));+ })();+ }, [who, params, editor, openDoc, router]);++ const doc = editor.doc;+ const entry = doc ? entryForRecipe(doc.recipe) : undefined;++ // The address follows the open scene (replaced, never pushed); the first one keeps what it was opened with.+ const shown = useRef<string | null>(null);+ const href = view === "editor" && entry && doc ? kineticHref(entry, recipeStyle(doc)) : view === "picker" ? "/kinetic" : null;+ useEffect(() => {+ if (!href) return;+ if (shown.current === null) {+ shown.current = href;+ return;+ }+ if (shown.current === href) return;+ shown.current = href;+ router.replace(href, { scroll: false });+ }, [href, router]);++ // The draft: the open recipe, per viewer and scene, a moment after each change.+ useEffect(() => {+ if (view !== "editor" || !doc || !entry || !who) return;+ const id = setTimeout(() => writeDraft(who, entry.slug, doc), 300);+ return () => clearTimeout(id);+ }, [doc, entry, who, view]);++ // While it finds out who is looking, the opening screen shows at once (as the static page does) unless the address+ // names a scene or a saved result.+ if (view === "loading" && (params.has("scene") || params.has("from"))) return <div className="min-h-[60svh]" aria-busy="true" />;+ if (view === "loading" || view === "picker" || !doc || !entry)+ return (+ <ScenePicker+ onOpen={(e: KineticEntry, x?: KineticExample) => {+ // Opened from the opening screen: the address follows to the scene from here.+ shown.current ??= "/kinetic";+ window.scrollTo({ top: 0 });+ void openDoc(e, { style: x?.style, fresh: !!x, example: x });+ }}+ />+ );+ return (+ <Editor+ editor={editor}+ doc={doc}+ entry={entry}+ missing={missing}+ onBack={() => setView("picker")}+ onScene={(to) => {+ if (to.slug === entry.slug) return;+ setMissing(new Set());+ const draft = who ? readDraft(who, to.slug) : null;+ const n = draft ? normalizeKinetic(draft.recipe) : null;+ editor.open(n && n.entry.slug === to.slug ? { recipe: n.recipe, logo: draft!.logo } : switchScene(doc, to, brandOf(doc)));+ }}+ />+ );+}diff --git a/src/components/kinetic/preset-row.tsx b/src/components/kinetic/preset-row.tsxnew file mode 100644index 00000000..e2ffb35d--- /dev/null+++ b/src/components/kinetic/preset-row.tsx@@ -0,0 +1,48 @@+"use client";++import { Check } from "lucide-react";+import { PRESETS, presetOf, type PresetCategory } from "@/lib/motion/edit";+import type { Recipe } from "@/lib/motion/recipe";+import { cn } from "@/lib/utils";++/**+ * A category's presets (at most four), each with its one line of purpose. The one whose values the recipe has exactly+ * is marked; when none matches, "Custom" shows. Presets aren't stored: the label is worked out from the values, so undo+ * and redo keep it right.+ */+export function PresetRow({ category, recipe, onPick, label }: { category: PresetCategory; recipe: Recipe; onPick: (id: string) => void; label: string }) {+ const current = presetOf(category, recipe);+ return (+ <div className="min-w-0" data-kinetic-presets={category}>+ <p className="mb-1.5 flex items-center gap-2 text-[12px] font-medium text-muted-foreground">+ {label}+ {current === "custom" && (+ <span className="rounded-full bg-secondary px-2 py-0.5 text-[11px] font-medium md:text-[12px] text-foreground" data-kinetic-custom>+ Custom+ </span>+ )}+ </p>+ <div role="radiogroup" aria-label={label} className="grid min-w-0 grid-cols-2 gap-1.5">+ {PRESETS[category].map((p) => {+ const on = current === p.id;+ return (+ <button+ key={p.id}+ type="button"+ role="radio"+ aria-checked={on}+ onClick={() => onPick(p.id)}+ className={cn("relative flex min-h-14 min-w-0 flex-col items-start justify-center rounded-xl border px-3 py-2 text-left outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring", on ? "border-foreground bg-foreground text-background" : "bg-background hover:bg-accent")}+ >+ <span className="flex w-full min-w-0 items-center gap-1 text-[13px] font-medium">+ <span className="truncate">{p.name}</span>+ {on && <Check className="ml-auto size-3.5 shrink-0" aria-hidden />}+ </span>+ <span className={cn("line-clamp-2 text-[11px] leading-snug md:text-[12px]", on ? "text-background/75" : "text-muted-foreground")}>{p.purpose}</span>+ </button>+ );+ })}+ </div>+ </div>+ );+}diff --git a/src/components/kinetic/preview.tsx b/src/components/kinetic/preview.tsxnew file mode 100644index 00000000..439ed5c7--- /dev/null+++ b/src/components/kinetic/preview.tsx@@ -0,0 +1,387 @@+"use client";++import { Check, ChevronDown, Pause, Play } from "lucide-react";+import { useEffect, useMemo, useRef, useState } from "react";+import { measureText } from "@/components/ads/render";+import { loadClip, type ClipSource } from "@/components/motion/clip-source";+import { drawDisplayList, type Sources } from "@/components/motion/draw";+import { useMotionInputs, useReducedMotion, type MotionInputs } from "@/components/motion/player";+import { drawFrame } from "@/components/motion/render";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { videoNodeOf } from "@/lib/motion/display";+import type { Recipe } from "@/lib/motion/recipe";+import type { Scene, ScenePlan } from "@/lib/motion/scene";+import { exportSize, previewSize } from "@/lib/motion/sizes";+import { quantize } from "@/lib/motion/time";+import { cn } from "@/lib/utils";+import { readChoice, writeChoice } from "./draft";+import { usePlayhead, usePlaying, type TimeStore } from "./time-store";++/**+ * Kinetic's preview: the same scene code as the export, drawn at an absolute time on every animation frame. Its mode+ * (Auto, Fast, Balanced, Sharp) only sets how many pixels it draws and whether grain shows while it plays; it is never+ * part of the recipe and never read by the export, so it never changes a saved file.+ */++export const PREVIEW_MODES = ["auto", "fast", "balanced", "sharp"] as const;+export type PreviewMode = (typeof PREVIEW_MODES)[number];+export const PREVIEW_MODE_NAMES: Record<PreviewMode, { name: string; line: string }> = {+ auto: { name: "Auto", line: "Sharp when it can, lighter on a busy device" },+ fast: { name: "Fast", line: "Half the pixels, no grain while it plays" },+ balanced: { name: "Balanced", line: "Steady detail" },+ sharp: { name: "Sharp", line: "Full detail; a paused frame as it will save" },+};++export function usePreviewMode(): [PreviewMode, (m: PreviewMode) => void] {+ // Read at once: the editor only renders in the browser.+ const [mode, setMode] = useState<PreviewMode>(() => readChoice("preview", PREVIEW_MODES, "auto"));+ return [+ mode,+ (m) => {+ setMode(m);+ writeChoice("preview", m);+ },+ ];+}++export interface ClipInputs {+ source: ClipSource | null;+ info: { w: number; h: number; duration: number } | null;+ /** The clip couldn't be opened (gone or unreadable). */+ failed: boolean;+}++/** The recipe's clip (Kinetic's video layer), loaded as a muted video. */+export function useClipInputs(url: string | null | undefined): ClipInputs {+ const [state, setState] = useState<ClipInputs & { url: string | null }>({ url: null, source: null, info: null, failed: false });+ useEffect(() => {+ if (!url) return;+ let live = true;+ let src: ClipSource | null = null;+ const ctl = new AbortController();+ void loadClip(url, { signal: ctl.signal })+ .then((s) => {+ src = s;+ if (live) setState({ url, source: s, info: s.info, failed: false });+ else s.dispose();+ })+ .catch(() => live && setState({ url, source: null, info: null, failed: true }));+ return () => {+ live = false;+ ctl.abort();+ src?.dispose();+ };+ }, [url]);+ if (!url || state.url !== url) return { source: null, info: null, failed: false };+ return state;+}++/** Everything the preview and the renders need besides the recipe: the pictures, the fonts and the clip. */+export interface KineticInputs extends MotionInputs {+ clip: ClipInputs;+}++export function useKineticInputs(recipe: Recipe | null): KineticInputs {+ const inputs = useMotionInputs(recipe);+ const clip = useClipInputs(recipe?.layers?.video?.src);+ return useMemo(() => ({ ...inputs, clip, sources: clip.source ? { ...inputs.sources, clips: new Map([["clip", clip.source.el]]) } : inputs.sources }), [inputs, clip]);+}++/** A scene planned for a recipe with its inputs (memoised on the recipe's JSON). */+export function useKineticPlan(scene: Scene | null, recipe: Recipe | null, inputs: KineticInputs): ScenePlan | null {+ const key = recipe ? JSON.stringify(recipe) : "";+ const info = inputs.clip.info;+ return useMemo(() => {+ if (!scene || !recipe || !inputs.ready) return null;+ try {+ return scene.plan({ recipe, measure: measureText, logo: inputs.logo, images: inputs.images, outlines: inputs.outlines, ...(info && { clips: { clip: info } }) });+ } catch {+ return null;+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [scene, key, inputs.version, inputs.ready, info]);+}++declare global {+ interface Window {+ /** Set by an end-to-end test to read the preview's frame times. */+ __kineticStats?: { frames: number[] };+ }+}++export interface KineticPreviewProps {+ plan: ScenePlan | null;+ recipe: Recipe;+ inputs: KineticInputs;+ time: TimeStore;+ mode: PreviewMode;+ label: string;+ /** Where it rests with reduced motion (the scene's telling moment; its last frame by default). */+ hold?: number;+ className?: string;+ style?: React.CSSProperties;+}++/** The big preview canvas. It writes the playhead; the transport and the timeline read it. */+export function KineticPreview({ plan, recipe, inputs, time, mode, label, hold, className, style }: KineticPreviewProps) {+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const reduced = useReducedMotion();+ const playing = usePlaying(time);+ const [visible, setVisible] = useState(true);+ const [shown, setShown] = useState(true);+ const quality = useRef({ scale: 1, steps: 0, slow: [] as number[], fastSince: 0 });+ const sharpReq = useRef(0);+ const sharpCanvases = useRef<[HTMLCanvasElement, HTMLCanvasElement] | null>(null);+ useEffect(+ () => () => {+ for (const x of sharpCanvases.current ?? []) Object.assign(x, { width: 0, height: 0 });+ sharpCanvases.current = null;+ },+ [],+ );+ const duration = recipe.duration;+ const sources: Sources = inputs.sources;+ const clip = inputs.clip.source;++ useEffect(() => {+ const el = canvasRef.current;+ if (!el) return;+ const io = new IntersectionObserver(([e]) => setVisible(e.isIntersecting), { threshold: 0.01 });+ io.observe(el);+ const vis = () => setShown(!document.hidden);+ document.addEventListener("visibilitychange", vis);+ return () => {+ io.disconnect();+ document.removeEventListener("visibilitychange", vis);+ };+ }, []);++ // Reduced motion: the resting frame, and nothing plays until Play is pressed.+ useEffect(() => {+ if (reduced && plan) {+ time.setPlaying(false);+ time.set(Math.min(plan.rest, hold ?? plan.rest));+ }+ }, [reduced, plan, time, hold]);++ /** The backing size for a mode (`still`: a paused frame). */+ const backing = (still: boolean) => {+ const c = canvasRef.current!;+ const cap = previewSize(recipe.size);+ const dpr = Math.min(2, window.devicePixelRatio || 1);+ const css = c.clientWidth || cap.w;+ if (mode === "sharp") {+ const ex = exportSize(recipe.size);+ return Math.max(16, Math.round(Math.min(ex.w, css * dpr)));+ }+ let w = Math.min(cap.w, css * dpr);+ if (mode === "fast" && !still) w /= 2;+ if (mode === "auto" && !still) w *= quality.current.scale;+ return Math.max(16, Math.round(w));+ };++ const paint = (t: number, still: boolean) => {+ const c = canvasRef.current;+ if (!c || !plan) return;+ const w = backing(still);+ const h = Math.max(16, Math.round((w * plan.design.h) / plan.design.w));+ if (c.width !== w || c.height !== h) {+ c.width = w;+ c.height = h;+ }+ const ctx = c.getContext("2d", { alpha: false });+ if (!ctx) return;+ const list = plan.evaluate(t);+ const v = videoNodeOf(list);+ if (v && clip) clip.follow(v.time, !still && playing, mode === "fast" ? 0.25 : 1 / 30);+ drawDisplayList(ctx, list, sources, { grain: !(mode === "fast" && !still) });+ };++ /** Sharp, paused: the frame as it will save (export size, its motion blur), a quarter size first; the newest asked wins. */+ const renderView = (t: number) => {+ const c = canvasRef.current;+ if (!c || !plan) return;+ const id = ++sharpReq.current;+ const ex = exportSize(recipe.size);+ const step = (k: number) => {+ if (id !== sharpReq.current) return;+ const w = Math.max(16, Math.round(ex.w * k));+ const h = Math.max(16, Math.round(ex.h * k));+ // Two canvases kept for the component and resized (new ones per step add up against a phone's canvas memory).+ const pair = (sharpCanvases.current ??= [document.createElement("canvas"), document.createElement("canvas")]);+ const [target, scratch] = pair;+ for (const x of pair) {+ if (x.width !== w || x.height !== h) Object.assign(x, { width: w, height: h });+ }+ drawFrame(plan, t, target, scratch, sources, { fps: recipe.fps, samples: recipe.export.blurSamples, shutter: recipe.export.shutter, duration });+ if (id !== sharpReq.current) return;+ c.width = w;+ c.height = h;+ c.getContext("2d", { alpha: false })?.drawImage(target, 0, 0);+ if (k < 1) setTimeout(() => step(1), 30);+ };+ setTimeout(() => step(0.25), 0);+ };++ const moving = playing && visible && shown && !!plan;++ // A still frame (paused, scrubbed, or a change while paused).+ useEffect(() => {+ if (moving || !plan) return;+ const t = Math.min(time.get(), plan.rest);+ if (mode === "sharp") {+ paint(t, true);+ renderView(t);+ } else paint(t, true);+ const redraw = () => (mode === "sharp" ? renderView(time.get()) : paint(time.get(), true));+ clip?.el.addEventListener("seeked", redraw);+ const off = time.onSeek((v) => {+ const at = Math.min(plan.rest, Math.max(0, v));+ time.set(at);+ if (mode === "sharp") {+ paint(at, true);+ renderView(at);+ } else paint(at, true);+ });+ return () => {+ off();+ clip?.el.removeEventListener("seeked", redraw);+ sharpReq.current++;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [moving, plan, mode, sources, clip]);++ useEffect(() => {+ if (!moving || !plan) return;+ let raf = 0;+ let from = time.get() >= plan.rest ? 0 : time.get();+ let start = performance.now();+ const off = time.onSeek((v) => {+ from = Math.min(plan.rest, Math.max(0, v));+ start = performance.now();+ });+ const tick = (now: number) => {+ let t = from + (now - start) / 1000;+ if (t >= duration) {+ t %= duration;+ from = 0;+ start = now - t * 1000;+ }+ time.set(t);+ const t0 = performance.now();+ paint(t, false);+ const spent = performance.now() - t0;+ window.__kineticStats?.frames.push(spent);+ if (mode === "auto") {+ // A slow second steps the backing store down (twice at most); three fast seconds step it back.+ const q = quality.current;+ q.slow.push(spent);+ if (q.slow.length >= 60) {+ const sorted = [...q.slow].sort((a, b) => a - b);+ const median = sorted[sorted.length >> 1];+ q.slow = [];+ if (median > 24 && q.steps < 2) {+ q.steps++;+ q.scale *= 0.75;+ q.fastSince = 0;+ } else if (median < 12 && q.steps > 0) {+ q.fastSince ||= now;+ if (now - q.fastSince > 3000) {+ q.steps--;+ q.scale /= 0.75;+ q.fastSince = 0;+ }+ } else q.fastSince = 0;+ }+ }+ raf = requestAnimationFrame(tick);+ };+ raf = requestAnimationFrame(tick);+ return () => {+ cancelAnimationFrame(raf);+ off();+ clip?.el.pause();+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [moving, plan, duration, mode, sources, clip]);++ return (+ <canvas+ ref={canvasRef}+ role="img"+ aria-label={label}+ data-kinetic-player="main"+ className={cn("block h-auto max-w-full rounded-2xl bg-muted shadow-soft", className)}+ style={{ aspectRatio: `${plan?.design.w ?? 9} / ${plan?.design.h ?? 16}`, ...style }}+ />+ );+}++const fmt = (t: number) => `${t.toFixed(1)} s`;++/** Play, the scrub bar (arrow keys a frame, Shift a second), the time and the preview mode. */+export function Transport({ time, duration, fps, rest, mode, onMode }: { time: TimeStore; duration: number; fps: number; rest: number; mode: PreviewMode; onMode: (m: PreviewMode) => void }) {+ const t = usePlayhead(time);+ const playing = usePlaying(time);+ const frame = 1 / fps;+ const go = (v: number) => {+ time.setPlaying(false);+ time.seek(Math.min(rest, Math.max(0, quantize(v + 1e-9, fps))));+ };+ return (+ <div className="flex min-w-0 items-center gap-1" data-kinetic-transport>+ <button+ type="button"+ onClick={() => {+ if (!playing && time.get() >= rest - 1e-6) time.seek(0);+ time.setPlaying(!playing);+ }}+ aria-label={playing ? "Pause" : "Play"}+ className="grid size-11 shrink-0 place-items-center rounded-full bg-foreground text-background outline-none hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"+ >+ {playing ? <Pause className="size-4" /> : <Play className="size-4 translate-x-px" />}+ </button>+ <input+ type="range"+ min={0}+ max={duration}+ step={frame}+ value={Math.min(duration, t)}+ aria-label="Time"+ aria-valuetext={fmt(t)}+ onChange={(e) => go(Number(e.target.value))}+ onKeyDown={(e) => {+ if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;+ e.preventDefault();+ const dir = e.key === "ArrowRight" ? 1 : -1;+ go(time.get() + dir * (e.shiftKey ? 1 : frame));+ }}+ className="k-range h-11 min-w-0 flex-1 cursor-pointer"+ style={{ "--fill": `${(Math.min(duration, t) / Math.max(1e-6, duration)) * 100}%` } as React.CSSProperties}+ />+ <span className="shrink-0 text-right text-[12px] tabular-nums text-muted-foreground" aria-live="off">+ {t.toFixed(1)} <span className="opacity-70">/ {fmt(duration)}</span>+ </span>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button type="button" className="inline-flex h-11 shrink-0 items-center gap-1 rounded-full px-2.5 text-[12px] font-medium text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring" aria-label={`Preview: ${PREVIEW_MODE_NAMES[mode].name}`}>+ <span className="hidden sm:inline">Preview:</span> {PREVIEW_MODE_NAMES[mode].name}+ <ChevronDown className="size-3.5" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-64">+ <DropdownMenuLabel className="text-[12px]">Preview quality (never changes what saves)</DropdownMenuLabel>+ {PREVIEW_MODES.map((m) => (+ <DropdownMenuItem key={m} onSelect={() => onMode(m)} className="min-h-11 items-start gap-2 py-2">+ <Check className={cn("mt-0.5 size-4 shrink-0", m === mode ? "opacity-100" : "opacity-0")} />+ <span className="min-w-0">+ <span className="block text-[13px] font-medium">{PREVIEW_MODE_NAMES[m].name}</span>+ <span className="block text-[12px] text-muted-foreground">{PREVIEW_MODE_NAMES[m].line}</span>+ </span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}diff --git a/src/components/kinetic/pro-panels.tsx b/src/components/kinetic/pro-panels.tsxnew file mode 100644index 00000000..9937c19e--- /dev/null+++ b/src/components/kinetic/pro-panels.tsx@@ -0,0 +1,145 @@+"use client";++import { useState } from "react";+import { applyPreset, dropTrackKey, keyIndexAt, paceOf, presetOf, PRESETS, putTrackKey, setValue, trackValue, type PresetCategory } from "@/lib/motion/edit";+import { templateOf, type KineticEntry } from "@/lib/motion/kinetic-catalog";+import { easyValue, setEasy, setPro, type KineticDoc } from "@/lib/motion/kinetic-doc";+import { CAMERA_MOVES, type CameraMoveId, type CurveSetId, type Recipe, type TrackId } from "@/lib/motion/recipe";+import { quantize } from "@/lib/motion/time";+import { Choices, Panel, Segmented, SliderField, type SliderFieldProps } from "./controls";+import { PresetRow } from "./preset-row";+import { usePlayhead, type TimeStore } from "./time-store";+import type { KineticEditor } from "./use-editor";++/**+ * Pro's four panels (Motion, Graphics, Appearance, Camera): the real values behind Easy's chips, the same for every+ * scene (the scene wrappers apply them), each category with its presets. The numbers a track can animate carry a key+ * button: the first key makes the track, and then the slider sets the key at the playhead.+ */++export const FEELS: { id: CurveSetId; label: string }[] = [+ { id: "smooth", label: "Smooth" },+ { id: "snappy", label: "Snappy" },+ { id: "springy", label: "Springy" },+ { id: "steady", label: "Steady" },+];++const MOVE_NAMES: Record<CameraMoveId, string> = { scene: "Scene's own", locked: "Locked off", push: "Push", drift: "Drift", rise: "Rise" };++const presetName = (c: PresetCategory, r: Recipe) => {+ const id = presetOf(c, r);+ return PRESETS[c].find((p) => p.id === id)?.name ?? "Custom";+};++const sec = (t: number) => `${t.toFixed(1)} s`;+const signed = (v: number) => `${v > 0 ? "+" : ""}${Math.round(v)}`;++export interface ProProps {+ doc: KineticDoc;+ entry: KineticEntry;+ editor: Pick<KineticEditor, "apply" | "end">;+ time: TimeStore;+}++/** A slider bound to a track id: the track's value at the playhead when there is one, else the plain value. */+export function useTrackSlider({ doc, editor, time }: Pick<ProProps, "doc" | "editor" | "time">) {+ const t = usePlayhead(time);+ const r = doc.recipe;+ const at = quantize(Math.min(t, r.duration), r.fps);+ return (id: TrackId, base: number, setBase?: (r: Recipe, v: number) => Recipe): Pick<SliderFieldProps, "value" | "onChange" | "onEnd" | "keyButton"> => {+ const track = r.tracks?.[id];+ const value = track ? trackValue(track, at) : base;+ const keyed = keyIndexAt(track, at, r.fps);+ const put = (rec: Recipe, v: number) => putTrackKey(rec, id, at, v, rec.fps) ?? rec;+ return {+ value,+ onChange: (v) => editor.apply((d) => setPro(d, (rec) => (rec.tracks?.[id] || !setBase ? put(rec, v) : setBase(rec, v))), { gesture: true }),+ onEnd: editor.end,+ keyButton: {+ label: keyed >= 0 ? `Remove the key at ${sec(at)}` : `Add a key at ${sec(at)}`,+ on: keyed >= 0,+ onPress: () => editor.apply((d) => setPro(d, (rec) => (keyed >= 0 ? dropTrackKey(rec, id, keyed) : put(rec, value)))),+ },+ };+ };+}++export function ProPanels({ doc, entry, editor, time }: ProProps) {+ const [open, setOpen] = useState<Record<string, boolean>>({ motion: true });+ const panel = (id: string) => ({ open: !!open[id], onOpen: (v: boolean) => setOpen((o) => ({ ...o, [id]: v })), id });+ const r = doc.recipe;+ const t = templateOf(entry);+ const track = useTrackSlider({ doc, editor, time });+ const pick = (c: PresetCategory) => (id: string) => editor.apply((d) => setPro(d, (rec) => applyPreset(c, id, rec)));+ const set = (path: string, v: string | number | boolean | undefined, gesture = false) => editor.apply((d) => setPro(d, (rec) => setValue(rec, path, v)), { gesture });+ const graphics = (t.easy ?? []).filter((g) => g.id !== "pace" && g.id !== "look");+ const easyPace = easyValue(doc, entry, "pace");+ const pace = r.motion?.pace ?? paceOf(r.controls);+ const look = easyValue(doc, entry, "look");+ const lookGroup = t.easy?.find((g) => g.id === "look");++ return (+ <div className="min-w-0 space-y-2.5" data-kinetic-pro>+ <Panel title="Motion" summary={presetName("motion", r)} {...panel("motion")}>+ <PresetRow category="motion" recipe={r} onPick={pick("motion")} label="Motion presets" />+ {entry.pro.pace && (+ <SliderField+ label="Pace"+ display={(v) => `x${v.toFixed(2)}`}+ value={pace}+ min={0.7}+ max={1.4}+ step={0.01}+ reverse+ ends={["Calmer", "Punchier"]}+ onChange={(v) => set("motion.pace", v, true)}+ onEnd={editor.end}+ note={r.motion?.pace === undefined ? `From Easy: ${t.easy?.find((g) => g.id === "pace")?.choices.find((c) => c.id === easyPace)?.label ?? "Calm"}` : undefined}+ />+ )}+ <Segmented label="Feel" choices={FEELS} value={r.motion?.curves ?? "smooth"} onChange={(v) => set("motion.curves", v)} />+ </Panel>++ {graphics.length > 0 && (+ <Panel title="Graphics" summary={graphics.map((g) => g.choices.find((c) => c.id === easyValue(doc, entry, g.id))?.label).filter(Boolean).join(" · ")} {...panel("graphics")}>+ {graphics.map((g) => (+ <Choices key={g.id} label={g.label} choices={g.choices} value={easyValue(doc, entry, g.id)} onChange={(c) => editor.apply((d) => setEasy(d, entry, g.id, c))} />+ ))}+ </Panel>+ )}++ <Panel title="Appearance" summary={presetName("appearance", r)} {...panel("appearance")}>+ <PresetRow category="appearance" recipe={r} onPick={pick("appearance")} label="Appearance presets" />+ {entry.pro.look && lookGroup && <Segmented label="Look" choices={lookGroup.choices} value={look} onChange={(c) => editor.apply((d) => setEasy(d, entry, "look", c))} />}+ <SliderField label="Contrast" display={(v) => signed(v * 100)} min={-0.5} max={0.5} step={0.01} scale={100} {...track("finish.contrast", r.finish?.contrast ?? 0, (rec, v) => setValue(rec, "finish.contrast", v))} />+ <SliderField label="Saturation" display={(v) => signed(v * 100)} min={-1} max={1} step={0.01} scale={100} {...track("finish.saturation", r.finish?.saturation ?? 0, (rec, v) => setValue(rec, "finish.saturation", v))} />+ <SliderField label="Grain" unit="%" display={(v) => `${(v * 100).toFixed(1)} %`} min={0} max={0.1} step={0.001} scale={100} {...track("finish.grain", r.finish?.grain ?? 0, (rec, v) => setValue(rec, "finish.grain", v))} />+ <SliderField label="Grain size" display={(v) => v.toFixed(1)} value={r.finish?.grainSize ?? 1.2} min={1} max={3} step={0.1} onChange={(v) => set("finish.grainSize", v, true)} onEnd={editor.end} />+ {entry.pro.light && (+ <Segmented+ label="Ground light"+ choices={[+ { id: "on", label: "On" },+ { id: "off", label: "Off" },+ ]}+ value={r.look?.light === false ? "off" : "on"}+ onChange={(v) => set("look.light", v === "off" ? false : undefined)}+ />+ )}+ </Panel>++ <Panel title="Camera" summary={MOVE_NAMES[r.camera?.move ?? "scene"]} {...panel("camera")}>+ <Choices label="Move" choices={CAMERA_MOVES.map((m) => ({ id: m, label: MOVE_NAMES[m] }))} value={r.camera?.move ?? "scene"} onChange={(m) => set("camera.move", m)} />+ <SliderField label="Strength" display={(v) => v.toFixed(2)} value={r.camera?.amount ?? 1} min={0} max={2} step={0.05} onChange={(v) => set("camera.amount", v, true)} onEnd={editor.end} disabled={!["push", "drift", "rise"].includes(r.camera?.move ?? "scene")} />+ <SliderField label="Breath" display={(v) => v.toFixed(2)} value={r.camera?.breath ?? 1} min={0} max={2} step={0.05} onChange={(v) => set("camera.breath", v, true)} onEnd={editor.end} disabled={r.camera?.move === "locked"} />+ <div className="space-y-3 border-t pt-3">+ <p className="text-[12px] text-muted-foreground">Add keys at the playhead to move the camera over time. The last frame keeps the framing of your last key.</p>+ <SliderField label="Zoom" unit="×" display={(v) => `x${v.toFixed(2)}`} min={0.8} max={1.25} step={0.01} {...track("camera.zoom", 1)} />+ <SliderField label="Pan across" display={(v) => signed(v * 100)} min={-0.1} max={0.1} step={0.005} scale={100} {...track("camera.x", 0)} />+ <SliderField label="Pan up and down" display={(v) => signed(v * 100)} min={-0.1} max={0.1} step={0.005} scale={100} {...track("camera.y", 0)} />+ <SliderField label="Roll" unit="°" display={(v) => `${v.toFixed(1)}°`} min={-10} max={10} step={0.1} {...track("camera.roll", 0)} />+ </div>+ </Panel>+ </div>+ );+}diff --git a/src/components/kinetic/scene-picker.tsx b/src/components/kinetic/scene-picker.tsxnew file mode 100644index 00000000..82c63260--- /dev/null+++ b/src/components/kinetic/scene-picker.tsx@@ -0,0 +1,222 @@+"use client";++import { Film, Layers, Play } from "lucide-react";+import { useEffect, useMemo, useRef, useState } from "react";+import { CoverArt, useCoverPlayback } from "@/components/template-cover";+import { MotionPlayer, useMotionInputs, usePlan, useScene } from "@/components/motion/player";+import { Viewer } from "@/components/studio/viewer";+import { useGenerations, useIsGuest } from "@/lib/api";+import type { Generation } from "@/lib/catalog/types";+import { exampleRecipe, KINETIC_EXAMPLES, KINETIC_SCENES, entryBySlug, restingTime, type KineticEntry, type KineticExample } from "@/lib/motion/kinetic-catalog";+import { templateCover } from "@/lib/template-covers";+import { cn } from "@/lib/utils";++/**+ * Kinetic's opening screen: four examples, every scene, and what the person made here before. The examples are drawn+ * live by the engine, each finished with its own look, and rest on their telling frame; a scene tile shows its cover.+ * On a screen with a pointer nothing moves until hovered or focused; on a phone, only the example most in view plays.+ * With reduced motion every tile keeps its still. A tile opens the editor on its scene.+ */++/** Everything Kinetic saves except versions (those live in the Versions sheet). */+export const MADE_FEATURES = ["kinetic", "kinetic-frame", "kinetic-sheet", "kinetic-canvas", "marketing-kinetic"];++const firstSentence = (s: string) => (s.match(/^[^.!?]*[.!?]/)?.[0] ?? s).trim();++const chipClass = "absolute top-2 left-2 inline-flex items-center gap-1 rounded-full bg-black/55 px-2 py-0.5 text-[11px] font-medium text-white backdrop-blur md:text-[12px]";+const playClass = "absolute right-2 bottom-2 grid size-6 place-items-center rounded-full bg-black/45 text-white backdrop-blur";++function SceneTile({ entry, onOpen, chip }: { entry: KineticEntry; onOpen: () => void; chip?: React.ReactNode }) {+ const cover = templateCover("marketing", entry.template);+ const { ref, playing, asked, handlers } = useCoverPlayback<HTMLButtonElement>(`kinetic/${entry.slug}`, cover, { auto: "touch" });+ return (+ <button ref={ref} type="button" {...handlers} onClick={onOpen} data-kinetic-tile={entry.slug} className="group/tile min-w-0 rounded-2xl text-left outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2">+ <span className="relative block aspect-[3/4] overflow-hidden rounded-2xl bg-muted transition-transform duration-300 ease-move group-hover/tile:scale-[1.015] motion-reduce:transition-none motion-reduce:group-hover/tile:scale-100">+ {cover && <CoverArt cover={cover} sizes="(max-width: 768px) 50vw, 20vw" playing={playing} asked={asked} />}+ {chip && <span className={chipClass}>{chip}</span>}+ <span className={playClass} aria-hidden>+ <Play className="size-3 fill-current" />+ </span>+ </span>+ <span className="mt-2 block truncate px-0.5 text-[13px] font-medium md:text-[14px]">{entry.name}</span>+ <span className="line-clamp-2 block px-0.5 text-[12px] leading-snug text-muted-foreground md:text-[13px]">{firstSentence(entry.blurb)}</span>+ </button>+ );+}++/** Whether a pointer can hover here (false on the server and first render: phones are the default). */+function useCanHover(): boolean {+ const [on, setOn] = useState(false);+ useEffect(() => {+ const mq = window.matchMedia("(hover: hover) and (pointer: fine)");+ const f = () => setOn(mq.matches);+ f();+ mq.addEventListener("change", f);+ return () => mq.removeEventListener("change", f);+ }, []);+ return on;+}++/** Which of the examples is most in view (phones play only that one). */+function useMostInView(count: number): [(i: number) => (el: HTMLElement | null) => void, number | null] {+ const els = useRef<(HTMLElement | null)[]>([]);+ const ratios = useRef<number[]>([]);+ const [best, setBest] = useState<number | null>(null);+ useEffect(() => {+ if (typeof IntersectionObserver === "undefined") return;+ const io = new IntersectionObserver(+ (entries) => {+ for (const e of entries) {+ const i = els.current.indexOf(e.target as HTMLElement);+ if (i >= 0) ratios.current[i] = e.intersectionRatio;+ }+ let top: number | null = null;+ ratios.current.forEach((r, i) => {+ if (r >= 0.6 && (top === null || r > ratios.current[top])) top = i;+ });+ setBest(top);+ },+ { threshold: [0, 0.25, 0.6, 0.8, 1] },+ );+ for (const el of els.current) if (el) io.observe(el);+ return () => io.disconnect();+ }, [count]);+ return [(i) => (el) => void (els.current[i] = el), best];+}++function ExampleTile({ example, onOpen, setRef, inView, canHover }: { example: KineticExample; onOpen: () => void; setRef: (el: HTMLElement | null) => void; inView: boolean; canHover: boolean }) {+ const entry = entryBySlug(example.slug)!;+ const cover = templateCover("marketing", entry.template);+ const recipe = useMemo(() => exampleRecipe(example), [example]);+ const inputs = useMotionInputs(recipe);+ const scene = useScene(recipe.scene);+ const plan = usePlan(scene, recipe, inputs);+ const [hover, setHover] = useState(false);+ const poster = plan ? restingTime(plan, recipe) : undefined;+ const ratio = plan ? `${plan.design.w} / ${plan.design.h}` : "4 / 5";+ return (+ <button+ ref={setRef}+ type="button"+ onClick={onOpen}+ onPointerEnter={(e) => e.pointerType === "mouse" && setHover(true)}+ onPointerLeave={(e) => e.pointerType === "mouse" && setHover(false)}+ onFocus={(e) => e.currentTarget.matches(":focus-visible") && setHover(true)}+ onBlur={() => setHover(false)}+ data-kinetic-tile={example.slug}+ data-kinetic-example={example.slug}+ className="group/tile min-w-0 rounded-2xl text-left outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"+ >+ <span className="relative grid aspect-[4/5] place-items-center overflow-hidden rounded-2xl bg-muted">+ {/* The scene's cover until the live drawing is ready, then the example itself. */}+ {!plan && cover && <CoverArt cover={cover} sizes="(max-width: 768px) 50vw, 25vw" />}+ {plan && (+ <span className="block h-full max-w-full" style={{ aspectRatio: ratio }}>+ <MotionPlayer plan={plan} sources={inputs.sources} size={recipe.size} duration={recipe.duration} fps={recipe.fps} label={`${example.label}: ${example.purpose}`} controls={false} active={canHover ? hover : inView} poster={poster} className="w-full" />+ </span>+ )}+ <span className={playClass} aria-hidden>+ <Play className="size-3 fill-current" />+ </span>+ </span>+ <span className="mt-2 block truncate px-0.5 text-[14px] font-medium md:text-[15px]">{example.label}</span>+ <span className="line-clamp-2 block px-0.5 text-[12px] leading-snug text-muted-foreground md:text-[13px]">{example.purpose}</span>+ </button>+ );+}++function MadeInKinetic() {+ const guest = useIsGuest();+ const list = useGenerations({ features: MADE_FEATURES, statuses: ["succeeded"], limit: 12 });+ const items = useMemo(() => (guest ? [] : (list.data ?? []).filter((g) => g.status === "succeeded" && g.outputs[0]).slice(0, 12)), [list.data, guest]);+ const [open, setOpen] = useState<Generation | null>(null);+ if (!items.length) return null;+ return (+ <section aria-labelledby="kinetic-made" className="min-w-0" data-kinetic-made-strip>+ <h2 id="kinetic-made" className="mb-3 font-heading text-[20px] leading-tight">+ Made in Kinetic+ </h2>+ <div className="scrollbar-none -mx-1 flex min-w-0 gap-2 overflow-x-auto px-1 pb-1">+ {items.map((g) => {+ const o = g.outputs[0];+ const poster = o.kind === "image" ? o.url : typeof o.meta?.poster === "string" ? o.meta.poster : undefined;+ // Its own shape when the size is known; otherwise the whole picture shows, never cropped.+ const sized = !!(o.width && o.height);+ return (+ <button key={g.id} type="button" onClick={() => setOpen(g)} aria-label={`Open ${(g.request.title ?? g.request.prompt ?? "saved result").slice(0, 80)}`} data-kinetic-made={g.id} className="relative h-36 shrink-0 overflow-hidden rounded-xl bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring" style={{ aspectRatio: sized ? `${o.width} / ${o.height}` : "4 / 5" }}>+ {poster ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={poster} alt="" className={cn("size-full", sized ? "object-cover" : "object-contain")} loading="lazy" />+ ) : (+ <video src={o.url} muted playsInline preload="metadata" className={cn("size-full", sized ? "object-cover" : "object-contain")} />+ )}+ {o.kind === "video" && (+ <span className={playClass} aria-hidden>+ <Play className="size-3 fill-current" />+ </span>+ )}+ </button>+ );+ })}+ </div>+ {open && <Viewer generation={open} index={0} onClose={() => setOpen(null)} />}+ </section>+ );+}++/** The opening screen as the static page sends it (its tiles start working once the page has loaded). */+export function ScenePickerShell() {+ return <ScenePicker onOpen={() => undefined} />;+}++export function ScenePicker({ onOpen }: { onOpen: (entry: KineticEntry, example?: KineticExample) => void }) {+ const canHover = useCanHover();+ const [refFor, best] = useMostInView(KINETIC_EXAMPLES.length);+ return (+ <div className="mx-auto w-full max-w-[1400px] min-w-0 space-y-10 px-4 pt-6 pb-16 sm:px-6 lg:px-8" data-kinetic-picker>+ <header className="max-w-2xl min-w-0">+ <h1 className="font-heading text-[32px] leading-[1.05] text-balance sm:text-[44px]">Fuobe Kinetic Motion</h1>+ <p className="mt-2 text-[15px] text-pretty text-muted-foreground sm:text-[17px]">Motion graphics in your brand, set in your exact words and drawn live in your browser.</p>+ </header>++ <section aria-labelledby="kinetic-examples" className="min-w-0">+ <h2 id="kinetic-examples" className="mb-3 font-heading text-[20px] leading-tight">+ Start from an example+ </h2>+ <div className="grid min-w-0 grid-cols-2 gap-3 md:grid-cols-4 md:gap-4" data-kinetic-examples>+ {KINETIC_EXAMPLES.map((x, i) => (+ <ExampleTile key={x.slug} example={x} setRef={refFor(i)} inView={best === i} canHover={canHover} onOpen={() => onOpen(entryBySlug(x.slug)!, x)} />+ ))}+ </div>+ </section>++ <section aria-labelledby="kinetic-all" className="min-w-0">+ <h2 id="kinetic-all" className="mb-3 font-heading text-[20px] leading-tight">+ All scenes+ </h2>+ <div className="grid min-w-0 grid-cols-2 gap-x-3 gap-y-5 md:grid-cols-3 xl:grid-cols-5" data-kinetic-scenes>+ {KINETIC_SCENES.map((e) => (+ <SceneTile+ key={e.slug}+ entry={e}+ onOpen={() => onOpen(e)}+ chip={+ e.slug === "end-card" ? (+ <>+ <Layers className="size-3" /> 5 styles+ </>+ ) : e.clip ? (+ <>+ <Film className="size-3" /> Over your clip+ </>+ ) : undefined+ }+ />+ ))}+ </div>+ </section>++ <MadeInKinetic />+ </div>+ );+}diff --git a/src/components/kinetic/time-store.ts b/src/components/kinetic/time-store.tsnew file mode 100644index 00000000..0b509719--- /dev/null+++ b/src/components/kinetic/time-store.ts@@ -0,0 +1,65 @@+"use client";++import { useSyncExternalStore } from "react";++/**+ * The editor's playhead, shared by the preview, the transport, the timeline and the key buttons without re-rendering+ * the whole editor on every frame: the preview writes it, readers subscribe (labels at most ten times a second).+ */+export interface TimeStore {+ get(): number;+ set(t: number): void;+ /** Whether the preview plays. */+ playing(): boolean;+ setPlaying(p: boolean): void;+ subscribe(fn: () => void): () => void;+ /** Asks the preview to go to a time (the timeline, the keys). */+ seek(t: number): void;+ onSeek(fn: (t: number) => void): () => void;+}++export function createTimeStore(): TimeStore {+ let t = 0;+ let play = false;+ let last = 0;+ const subs = new Set<() => void>();+ const seekers = new Set<(t: number) => void>();+ const emit = () => subs.forEach((f) => f());+ return {+ get: () => t,+ set(v) {+ t = v;+ const now = typeof performance !== "undefined" ? performance.now() : 0;+ // Readers hear at most ten times a second while it plays.+ if (!play || now - last > 100) {+ last = now;+ emit();+ }+ },+ playing: () => play,+ setPlaying(p) {+ if (p === play) return;+ play = p;+ emit();+ },+ subscribe(fn) {+ subs.add(fn);+ return () => void subs.delete(fn);+ },+ seek(v) {+ seekers.forEach((f) => f(v));+ },+ onSeek(fn) {+ seekers.add(fn);+ return () => void seekers.delete(fn);+ },+ };+}++export function usePlayhead(store: TimeStore): number {+ return useSyncExternalStore(store.subscribe, store.get, () => 0);+}++export function usePlaying(store: TimeStore): boolean {+ return useSyncExternalStore(store.subscribe, store.playing, () => false);+}diff --git a/src/components/kinetic/timeline.tsx b/src/components/kinetic/timeline.tsxnew file mode 100644index 00000000..c30d0feb--- /dev/null+++ b/src/components/kinetic/timeline.tsx@@ -0,0 +1,168 @@+"use client";++import { Diamond } from "lucide-react";+import { useMemo, useState } from "react";+import { dropTrackKey, groupsOf, isIdentityTiming, moveTrackKey, shotWindows } from "@/lib/motion/edit";+import { groupDefsFor } from "@/lib/motion/kinetic-groups";+import { setPro, type KineticDoc } from "@/lib/motion/kinetic-doc";+import type { TrackId } from "@/lib/motion/recipe";+import type { ScenePlan } from "@/lib/motion/scene";+import { cn } from "@/lib/utils";+import { usePlayhead, type TimeStore } from "./time-store";+import type { KineticEditor } from "./use-editor";++/**+ * The Timeline: the scene's motion groups as rows, each drawing its events at their real (retimed) times on a ruler,+ * then a lane per parameter track with its keys. Tapping a row opens its timing; tapping a key moves the playhead to it.+ * The ruler runs the clip's whole length, the last stretch marked as the hold on the rest frame.+ */++export const TRACK_NAMES: Record<TrackId, string> = {+ "camera.zoom": "Zoom",+ "camera.x": "Pan across",+ "camera.y": "Pan up and down",+ "camera.roll": "Roll",+ "finish.contrast": "Contrast",+ "finish.saturation": "Saturation",+ "finish.grain": "Grain",+ "clip.dim": "Clip dim",+};++const pct = (t: number, total: number) => `${Math.max(0, Math.min(100, (t / Math.max(1e-6, total)) * 100))}%`;++function Playhead({ time, total }: { time: TimeStore; total: number }) {+ const t = usePlayhead(time);+ return <span aria-hidden className="pointer-events-none absolute inset-y-0 w-0.5 -translate-x-1/2 rounded-full bg-primary" style={{ left: pct(t, total) }} />;+}++function Ruler({ total, rest }: { total: number; rest: number }) {+ const marks = Array.from({ length: Math.floor(total + 1e-6) + 1 }, (_, i) => i);+ return (+ <div className="relative h-6 text-[11px] text-muted-foreground tabular-nums md:text-[12px]" aria-hidden>+ {rest < total - 0.05 && (+ <span className="absolute inset-y-0 right-0 flex items-start justify-end rounded-sm bg-[repeating-linear-gradient(135deg,var(--muted)_0_4px,transparent_4px_8px)] pr-1" style={{ left: pct(rest, total) }}>+ <span className="bg-card px-1">Hold</span>+ </span>+ )}+ {marks.map((s) => (+ <span key={s} className={cn("absolute", s === 0 ? "" : s >= total - 1e-6 ? "-translate-x-full" : "-translate-x-1/2")} style={{ left: pct(s, total) }}>+ {s}s+ </span>+ ))}+ </div>+ );+}++export function Timeline({ plan, doc, time, editor, onGroup }: { plan: ScenePlan; doc: KineticDoc; time: TimeStore; editor: Pick<KineticEditor, "apply">; onGroup: (id: string) => void }) {+ const r = doc.recipe;+ const total = Math.max(plan.rest, r.duration);+ const windows = useMemo(() => shotWindows(plan), [plan]);+ const groups = useMemo(() => groupsOf(groupDefsFor(r.scene), plan.timeline.events, windows), [plan, windows, r.scene]);+ const [sel, setSel] = useState<{ id: TrackId; i: number } | null>(null);+ const tracks = Object.entries(r.tracks ?? {}) as [TrackId, NonNullable<NonNullable<typeof r.tracks>[TrackId]>][];+ const label = "w-24 shrink-0 truncate pr-2 text-left text-[12px] font-medium sm:w-28";++ return (+ <section aria-labelledby="kinetic-timing" className="min-w-0 rounded-2xl border bg-card p-3" data-kinetic-timeline>+ <div className="mb-1 flex min-w-0 flex-wrap items-baseline justify-between gap-x-3">+ <h3 id="kinetic-timing" className="text-[14px] font-medium">+ Timing+ </h3>+ <p className="text-[12px] text-muted-foreground">Tap a part to change its timing</p>+ </div>+ <div className="flex min-w-0">+ <span className={label} />+ <div className="min-w-0 flex-1">+ <Ruler total={total} rest={plan.rest} />+ </div>+ </div>+ <div className="relative min-w-0">+ {windows.map((w, wi) => (+ <div key={wi} className="min-w-0">+ {windows.length > 1 && <p className="mt-1 mb-0.5 text-[12px] font-medium text-muted-foreground">Shot {wi + 1}</p>}+ {groups+ .filter((g) => g.window === wi)+ .map((g) => {+ const retimed = !isIdentityTiming(r.groups?.[g.id]);+ return (+ <button key={g.id} type="button" onClick={() => onGroup(g.id)} data-kinetic-group={g.id} aria-label={`${g.label} timing${retimed ? ", retimed" : ""}`} className="flex h-11 w-full min-w-0 items-center rounded-lg outline-none hover:bg-accent/60 focus-visible:ring-2 focus-visible:ring-ring">+ <span className={label}>+ {g.label}+ {retimed && <span className="ml-1 inline-block size-1.5 rounded-full bg-primary align-middle" aria-hidden />}+ </span>+ <span className="relative h-6 min-w-0 flex-1 rounded bg-secondary/60">+ {g.camera ? (+ <span className={cn("absolute inset-y-2 rounded", retimed ? "bg-primary" : "bg-muted-foreground")} style={{ left: pct(w[0], total), width: pct(w[1] - w[0], total) }} />+ ) : (+ // One solid tone (overlapping beats never read as a second colour); a retimed part in the brand colour.+ g.events.map((e) => <span key={e.id} className={cn("absolute inset-y-1 rounded-sm", retimed ? "bg-primary" : "bg-muted-foreground")} style={{ left: pct(Math.max(0, e.start), total), width: `max(2px, ${pct(e.dur, total)})` }} />)+ )}+ </span>+ </button>+ );+ })}+ </div>+ ))}+ {tracks.length > 0 && <p className="mt-2 mb-0.5 text-[12px] font-medium text-muted-foreground">Keys</p>}+ {tracks.map(([id, tr]) => (+ <div key={id} className="flex h-11 min-w-0 items-center" data-kinetic-track={id}>+ <span className={label}>{TRACK_NAMES[id]}</span>+ <span className="relative h-11 min-w-0 flex-1">+ <span className="absolute inset-x-0 top-1/2 h-px bg-border" aria-hidden />+ {tr.keys.map((k, i) => {+ const on = sel?.id === id && sel.i === i;+ return (+ <button+ key={i}+ type="button"+ aria-label={`${TRACK_NAMES[id]} key at ${k.t.toFixed(2)} s`}+ aria-pressed={on}+ onClick={() => {+ setSel({ id, i });+ time.setPlaying(false);+ time.seek(k.t);+ }}+ onKeyDown={(e) => {+ if (e.key === "ArrowLeft" || e.key === "ArrowRight") {+ e.preventDefault();+ const t = k.t + (e.key === "ArrowRight" ? 1 : -1) / r.fps;+ editor.apply((d) => setPro(d, (rec) => moveTrackKey(rec, id, i, t, rec.fps)));+ time.seek(Math.max(0, t));+ } else if (e.key === "Delete" || e.key === "Backspace") {+ e.preventDefault();+ editor.apply((d) => setPro(d, (rec) => dropTrackKey(rec, id, i)));+ setSel(null);+ }+ }}+ className="absolute top-0 grid size-11 -translate-x-1/2 place-items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring"+ style={{ left: pct(k.t, total) }}+ >+ <Diamond className={cn("size-3.5", on ? "fill-primary text-primary" : "fill-foreground text-foreground")} />+ </button>+ );+ })}+ </span>+ </div>+ ))}+ <div className="pointer-events-none absolute inset-y-0 right-0 left-24 sm:left-28">+ <Playhead time={time} total={total} />+ </div>+ </div>+ {sel && r.tracks?.[sel.id]?.keys[sel.i] && (+ <div className="mt-2 flex items-center gap-2">+ <button+ type="button"+ onClick={() => {+ editor.apply((d) => setPro(d, (rec) => dropTrackKey(rec, sel.id, sel.i)));+ setSel(null);+ }}+ className="h-11 rounded-full bg-secondary px-4 text-[13px] font-medium outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"+ >+ Delete key+ </button>+ <p className="min-w-0 text-[12px] text-muted-foreground">Arrow keys move it one frame.</p>+ </div>+ )}+ </section>+ );+}diff --git a/src/components/kinetic/use-editor.ts b/src/components/kinetic/use-editor.tsnew file mode 100644index 00000000..03ce1b78--- /dev/null+++ b/src/components/kinetic/use-editor.ts@@ -0,0 +1,72 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import type { KineticDoc } from "@/lib/motion/kinetic-doc";+import { canRedo, canUndo, change, redo, restore, settle, SETTLE_MS, startHistory, undo, type History } from "./history";++/**+ * The editor's document with undo and redo for this visit. `apply` makes a change: a plain one is a step of its own; a+ * gesture's changes (a drag, typing) join one step until it settles (`end`, or SETTLE_MS after the last change).+ * Ctrl/⌘ Z undoes; Ctrl/⌘ Shift Z and Ctrl Y redo (not while typing in a field, where the browser's own undo works).+ */+export function useKineticEditor() {+ const [h, setH] = useState<History<KineticDoc> | null>(null);+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);++ const end = useCallback(() => {+ if (timer.current) clearTimeout(timer.current);+ timer.current = null;+ setH((x) => (x ? settle(x) : x));+ }, []);++ const apply = useCallback(+ (f: (d: KineticDoc) => KineticDoc, o: { gesture?: boolean } = {}) => {+ setH((x) => (x ? change(x, f(x.present), o) : x));+ if (o.gesture) {+ if (timer.current) clearTimeout(timer.current);+ timer.current = setTimeout(end, SETTLE_MS);+ }+ },+ [end],+ );++ /** Opens a document: the first one starts the history; later ones (another scene) are a step. */+ const open = useCallback((doc: KineticDoc) => setH((x) => (x ? change(settle(x), doc) : startHistory(doc))), []);+ const restoreTo = useCallback((doc: KineticDoc) => setH((x) => (x ? restore(x, doc) : startHistory(doc))), []);+ const doUndo = useCallback(() => setH((x) => (x ? undo(x) : x)), []);+ const doRedo = useCallback(() => setH((x) => (x ? redo(x) : x)), []);++ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (!(e.ctrlKey || e.metaKey) || e.altKey) return;+ const el = e.target as HTMLElement | null;+ if (el && (el.isContentEditable || (el.tagName === "INPUT" && (el as HTMLInputElement).type !== "range") || el.tagName === "TEXTAREA")) return;+ const k = e.key.toLowerCase();+ if (k === "z" && !e.shiftKey) {+ e.preventDefault();+ doUndo();+ } else if ((k === "z" && e.shiftKey) || (k === "y" && !e.metaKey)) {+ e.preventDefault();+ doRedo();+ }+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [doUndo, doRedo]);++ useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []);++ return {+ doc: h?.present ?? null,+ apply,+ end,+ open,+ restore: restoreTo,+ undo: doUndo,+ redo: doRedo,+ canUndo: !!h && canUndo(h),+ canRedo: !!h && canRedo(h),+ };+}++export type KineticEditor = ReturnType<typeof useKineticEditor>;diff --git a/src/components/kinetic/versions-sheet.tsx b/src/components/kinetic/versions-sheet.tsxnew file mode 100644index 00000000..7a885753--- /dev/null+++ b/src/components/kinetic/versions-sheet.tsx@@ -0,0 +1,128 @@+"use client";++import { History, Loader2, X } from "lucide-react";+import { useMemo, useRef, useState } from "react";+import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";+import { useIsGuest, useLibrary } from "@/lib/api";+import type { Generation } from "@/lib/catalog/types";+import { normalizeKinetic } from "@/lib/motion/kinetic-catalog";+import { cn } from "@/lib/utils";+import { iconButton, sheetClass } from "./controls";+import { jobLine, type KineticJobs } from "./jobs";++/**+ * Versions: small pictures of the rest frame saved as results, each carrying its recipe. Restore loads one; when what+ * is open differs from the last version saved or restored, it asks first. Either way what was open goes on the undo+ * stack, so Undo brings it back. A guest sees only the Save version button (which asks them to sign up).+ */++const when = (ms: number) => new Date(ms).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });++export const recipeOfResult = (g: Generation): unknown => (g.request.params?.extra as Record<string, unknown> | undefined)?.motion;++export function VersionsSheet({ open, onClose, side, jobs, onSaveVersion, onRestore, dirty }: { open: boolean; onClose: () => void; side: "bottom" | "right"; jobs: KineticJobs; onSaveVersion: () => Promise<unknown>; onRestore: (g: Generation) => void; dirty: boolean }) {+ const guest = useIsGuest();+ const list = useLibrary({ features: ["kinetic-version"], statuses: ["succeeded"], limit: 24 }, { enabled: open && !guest });+ const items = useMemo(() => (list.data?.pages.flat() ?? []).filter((g) => g.status === "succeeded" && g.outputs[0]), [list.data]);+ const [ask, setAsk] = useState<Generation | null>(null);+ const busy = jobs.job?.kind === "version";+ const title = useRef<HTMLHeadingElement>(null);+ const restore = (g: Generation) => {+ if (dirty) setAsk(g);+ else onRestore(g);+ };+ return (+ <>+ <Sheet open={open} onOpenChange={(v) => !v && onClose()}>+ <SheetContent+ side={side}+ showCloseButton={false}+ className={sheetClass}+ data-kinetic-sheet="versions"+ onOpenAutoFocus={(e) => {+ e.preventDefault();+ title.current?.focus();+ }}+ >+ <SheetHeader className="flex-row items-start gap-2 pb-3">+ <div className="min-w-0 flex-1">+ <SheetTitle ref={title} tabIndex={-1} className="outline-none">+ Versions+ </SheetTitle>+ <SheetDescription className="text-[13px]">Keep this state to come back to. Each version is saved with your results.</SheetDescription>+ </div>+ <button type="button" onClick={onClose} aria-label="Close" className={iconButton}>+ <X className="size-4" />+ </button>+ </SheetHeader>+ <div className="min-w-0 space-y-3 px-4 pb-4">+ <button type="button" data-kinetic-save="version" onClick={() => void onSaveVersion()} disabled={!!jobs.job} className="flex h-12 w-full items-center justify-center gap-2 rounded-xl bg-primary px-4 text-[14px] font-medium text-primary-foreground outline-none hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50">+ {busy ? <Loader2 className="size-4 animate-spin" /> : <History className="size-4" />}+ {busy ? jobLine(jobs.job) : jobs.job ? "Saving another one…" : "Save version"}+ </button>+ {!guest && items.length > 0 && (+ <ul className="grid grid-cols-2 gap-2" data-kinetic-versions>+ {items.map((g) => {+ const ok = !!normalizeKinetic(recipeOfResult(g));+ return (+ <li key={g.id} className="min-w-0 overflow-hidden rounded-xl border bg-card">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={g.outputs[0].url} alt="" loading="lazy" className="aspect-square w-full bg-muted object-contain" />+ <div className="min-w-0 p-2">+ <p className="truncate text-[12px] font-medium">{(g.request.title ?? "").replace(/^Version · /, "") || "Version"}</p>+ <p className="text-[12px] text-muted-foreground tabular-nums">{when(g.createdAt)}</p>+ <button type="button" disabled={!ok} onClick={() => restore(g)} data-kinetic-restore={g.id} className={cn("mt-1 h-11 w-full rounded-full bg-secondary text-[13px] font-medium outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-40")}>+ Restore+ </button>+ </div>+ </li>+ );+ })}+ </ul>+ )}+ {!guest && list.isSuccess && items.length === 0 && <p className="py-2 text-center text-[13px] text-muted-foreground">Your saved versions show here.</p>}+ {!guest && list.hasNextPage && (+ <button type="button" onClick={() => void list.fetchNextPage()} disabled={list.isFetchingNextPage} className="h-11 w-full rounded-full border text-[13px] font-medium outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring">+ Show more+ </button>+ )}+ </div>+ </SheetContent>+ </Sheet>+ <AlertDialog open={!!ask} onOpenChange={(v) => !v && setAsk(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Keep what you have?</AlertDialogTitle>+ <AlertDialogDescription>Save it as a version first. Either way, Undo brings it back.</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel className="h-11">Cancel</AlertDialogCancel>+ <AlertDialogAction+ className="h-11"+ variant="outline"+ onClick={() => {+ const g = ask;+ setAsk(null);+ if (g) onRestore(g);+ }}+ >+ Don't save+ </AlertDialogAction>+ <AlertDialogAction+ className="h-11"+ onClick={() => {+ const g = ask;+ setAsk(null);+ // Restores only once the version is saved (a failed save keeps what is open).+ if (g) void onSaveVersion().then((saved) => saved && onRestore(g));+ }}+ >+ Save version+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ );+}diff --git a/src/components/marketing/kinetic-template.tsx b/src/components/marketing/kinetic-template.tsxindex 92eff5f4..e38e643e 100644--- a/src/components/marketing/kinetic-template.tsx+++ b/src/components/marketing/kinetic-template.tsx@@ -39,7 +39,7 @@ const SAMPLES: { id: keyof typeof SHOWCASE_PRODUCTS; label: string }[] = [{ id: "heel", label: "Sample: red heel" },];-function PicturePicker({ value, onChange, owner }: { value: string | null | undefined; onChange: (url: string | null) => void; owner: boolean }) {+export function PicturePicker({ value, onChange, owner }: { value: string | null | undefined; onChange: (url: string | null) => void; owner: boolean }) {const [own, setOwn] = useState<SlotValue | null>(null);const [product, setProduct] = useState<ProductChoice | null>(null);const tile = (on: boolean) => cn("relative size-14 shrink-0 overflow-hidden rounded-xl bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring", on && "ring-2 ring-primary ring-offset-2 ring-offset-background");diff --git a/src/components/motion/clip-source.ts b/src/components/motion/clip-source.tsnew file mode 100644index 00000000..ce631828--- /dev/null+++ b/src/components/motion/clip-source.ts@@ -0,0 +1,189 @@+"use client";++/**+ * The person's own clip as a picture source for Kinetic's video layer: one muted, inline <video> per clip, read from+ * its stored file (same origin, so the canvas stays readable). The preview lets it play natively and puts it back in+ * step when it drifts by more than a frame; an export seeks it exactly before every frame (seeked, then the next+ * presented frame), so every motion-blur moment of a frame draws the same picture. A seek that doesn't land fails the+ * render with a clear message rather than drawing whatever frame the video shows.+ */++/** Seeks land this far past the asked time, so a time exactly on a frame boundary never shows the frame before. */+const SEEK_NUDGE = 1e-4;+/** How long a clip may take to show its first frame, and one seek to land (it is tried twice). */+const LOAD_MS = 15_000;+const SEEK_MS = 4_000;++export const CLIP_OPEN_ERROR = "We can't open that clip.";+export const CLIP_SEEK_ERROR = "We can't read that clip. Try an MP4 or WebM clip saved on Fuobe.";++export interface ClipSource {+ url: string;+ el: HTMLVideoElement;+ info: { w: number; h: number; duration: number };+ /** Puts the clip exactly on the picture shown at `time` (seconds into the clip). Rejects when the seek doesn't land. */+ seek(time: number): Promise<void>;+ /** The preview: plays natively from `time` while `playing`, re-seeking when it drifts past `tolerance` seconds. */+ follow(time: number, playing: boolean, tolerance: number): void;+ dispose(): void;+}++const aborted = () => new DOMException("Stopped", "AbortError");++/** Waits for `ev` on the video; rejects on its error event, after `ms`, or when `signal` aborts. */+function waitFor(el: HTMLVideoElement, ev: string, ms: number, signal?: AbortSignal, message = CLIP_SEEK_ERROR): Promise<void> {+ return new Promise<void>((resolve, reject) => {+ if (signal?.aborted) return reject(aborted());+ const off = () => {+ clearTimeout(timer);+ el.removeEventListener(ev, ok);+ el.removeEventListener("error", bad);+ signal?.removeEventListener("abort", stop);+ };+ const ok = () => {+ off();+ resolve();+ };+ const bad = () => {+ off();+ reject(new Error(message));+ };+ const stop = () => {+ off();+ reject(aborted());+ };+ const timer = setTimeout(bad, ms);+ el.addEventListener(ev, ok, { once: true });+ el.addEventListener("error", bad, { once: true });+ signal?.addEventListener("abort", stop, { once: true });+ });+}++type FrameMeta = { mediaTime: number };+type FrameCallbackVideo = HTMLVideoElement & { requestVideoFrameCallback?: (cb: (now: number, meta: FrameMeta) => void) => number };++/**+ * The next presented frame's media time (requestVideoFrameCallback), at most `ms`; null when none was presented in time+ * (the picture didn't change) or the browser has no frame callback.+ */+function nextFrame(el: FrameCallbackVideo, ms = 250): Promise<number | null> {+ if (!el.requestVideoFrameCallback) return Promise.resolve(null);+ return new Promise((resolve) => {+ let done = false;+ const finish = (t: number | null) => {+ if (done) return;+ done = true;+ resolve(t);+ };+ setTimeout(() => finish(null), ms);+ el.requestVideoFrameCallback!((_now, meta) => finish(meta.mediaTime));+ });+}++/** Loads a stored clip (its first frame decoded) as a picture source; gives up after 15 s or when `signal` aborts. */+export async function loadClip(url: string, o: { signal?: AbortSignal } = {}): Promise<ClipSource> {+ const el = document.createElement("video") as FrameCallbackVideo;+ el.muted = true;+ el.playsInline = true;+ el.preload = "auto";+ el.crossOrigin = "anonymous";+ el.setAttribute("playsinline", "");+ el.setAttribute("muted", "");+ const release = () => {+ el.pause();+ el.removeAttribute("src");+ el.load();+ };+ try {+ const ready = waitFor(el, "loadeddata", LOAD_MS, o.signal, CLIP_OPEN_ERROR);+ el.src = url;+ // Some browsers (iOS) never start loading a video that isn't on the page until asked.+ el.load();+ if (el.readyState < 2) await ready;+ else void ready.catch(() => undefined);+ } catch (e) {+ release();+ throw e;+ }++ /**+ * What the video shows: the presented frame's media time, and the clip's frame length once two presented frames+ * one frame apart have been seen. A seek that lands inside the frame on show (an export faster than the clip) skips+ * waiting for a new frame that never comes.+ */+ let shown: number | null = null;+ let lastTarget: number | null = null;+ const gaps: number[] = [];+ const frameLen = () => {+ if (gaps.length < 2) return null;+ const min = Math.min(...gaps);+ // Two gaps of the same smallest size: that is one frame of the clip.+ return gaps.filter((g) => Math.abs(g - min) < 1e-3).length >= 2 ? min : null;+ };++ let pending: Promise<void> = Promise.resolve();+ const signal = o.signal;+ const seekNow = async (time: number) => {+ if (signal?.aborted) throw aborted();+ const target = Math.max(0, Math.min(el.duration || time, time + SEEK_NUDGE));+ if (!el.paused) el.pause();+ if (Math.abs(el.currentTime - target) < 1e-6 && !el.seeking) return;+ const step = lastTarget === null ? null : target - lastTarget;+ lastTarget = target;+ const f = frameLen();+ // The same picture: the clip's frame on show covers this time, and the export steps finer than the clip's frames.+ if (f && shown !== null && step !== null && step > 0 && f > step * 1.2 && target >= shown - 1e-6 && target < shown + f - 1e-3) return;+ let presented: Promise<number | null> = Promise.resolve(null);+ for (let attempt = 0; ; attempt++) {+ const seeked = waitFor(el, "seeked", SEEK_MS, signal);+ presented = nextFrame(el);+ el.currentTime = target;+ try {+ await seeked;+ break;+ } catch (e) {+ if ((e as Error).name === "AbortError" || attempt >= 1) throw e;+ }+ }+ const t = await presented;+ if (t === null) {+ // No new frame: the picture on show stays (its time is known only when a frame was presented).+ if (!el.requestVideoFrameCallback) shown = null;+ return;+ }+ if (shown !== null && t > shown + 1e-4) {+ gaps.push(t - shown);+ if (gaps.length > 24) gaps.shift();+ }+ shown = t;+ };+ return {+ url,+ el,+ info: { w: el.videoWidth, h: el.videoHeight, duration: el.duration },+ seek(time) {+ // One seek at a time, in order; a failed seek doesn't block the ones after it from failing on their own.+ const next = pending.catch(() => undefined).then(() => seekNow(time));+ pending = next;+ return next;+ },+ follow(time, playing, tolerance) {+ shown = null;+ lastTarget = null;+ const target = Math.max(0, Math.min(el.duration, time));+ if (!playing) {+ if (!el.paused) el.pause();+ if (Math.abs(el.currentTime - target) > tolerance / 2 && !el.seeking) el.currentTime = target + SEEK_NUDGE;+ return;+ }+ if (target >= el.duration - 0.01) {+ // Held on its last frame.+ if (!el.paused) el.pause();+ return;+ }+ if (Math.abs(el.currentTime - target) > tolerance && !el.seeking) el.currentTime = target;+ if (el.paused) void el.play().catch(() => undefined);+ },+ dispose: release,+ };+}diff --git a/src/components/motion/draw.ts b/src/components/motion/draw.tsindex 580e0bb1..3ffa7a6b 100644--- a/src/components/motion/draw.ts+++ b/src/components/motion/draw.ts@@ -1,6 +1,7 @@"use client";import { IDENTITY, multiply, type ClipShape, type DisplayList, type DisplayNode, type Gradient, type Matrix, type Paint, type Stroke } from "@/lib/motion/display";+import { cssFilter, GRAIN_GAIN, GRAIN_TILE, grainOffset, grainScale, grainTile, gradePixels, type Finish } from "@/lib/motion/finish";import type { LogoInfo, LogoPath } from "@/lib/motion/scene";/**@@ -15,6 +16,8 @@ type AnyCanvas = HTMLCanvasElement | OffscreenCanvas;export interface Sources {/** Pictures by key ("logo", "product"). */images: Map<string, CanvasImageSource>;+ /** The person's clips by key ("clip"): a muted video element each, at the frame the caller put it on. */+ clips?: Map<string, CanvasImageSource>;}const paths = new Map<string, Path2D>();@@ -47,22 +50,43 @@ function pathLength(d: string): number {return n;}-let filterOk: boolean | null = null;-/** Whether this browser's canvas takes a CSS filter (blur); where it can't, scenes keep their scale moves only. */-function canFilter(ctx: Ctx): boolean {- if (filterOk === null) {+/**+ * Whether a canvas of this kind really draws through a CSS filter, tested on pixels once per kind: where canvas filters+ * are missing (Safari before 18), assigning `ctx.filter` only makes a plain property that reads back the same text, so a+ * read-back test would say yes. A red pixel drawn with saturate(0) must come out grey.+ */+const filterWorks = new Map<string, boolean>();+function canvasFilters(ctx: Ctx): boolean {+ const html = typeof HTMLCanvasElement !== "undefined" && ctx.canvas instanceof HTMLCanvasElement;+ const kind = html ? "html" : "offscreen";+ let ok = filterWorks.get(kind);+ if (ok === undefined) {+ ok = false;try {- const before = ctx.filter;- ctx.filter = "blur(1px)";- filterOk = ctx.filter === "blur(1px)";- ctx.filter = before;+ const make = (): AnyCanvas => (html ? Object.assign(document.createElement("canvas"), { width: 1, height: 1 }) : new OffscreenCanvas(1, 1));+ const src = make();+ const s = src.getContext("2d") as Ctx;+ s.fillStyle = "rgb(200,40,40)";+ s.fillRect(0, 0, 1, 1);+ const dst = make();+ const d = dst.getContext("2d", { willReadFrequently: true }) as Ctx;+ if ("filter" in Object.getPrototypeOf(d)) {+ d.filter = "saturate(0)";+ d.drawImage(src, 0, 0);+ const [r, g, b] = d.getImageData(0, 0, 1, 1).data;+ ok = Math.abs(r - g) < 12 && Math.abs(g - b) < 12;+ }} catch {- filterOk = false;+ ok = false;}+ filterWorks.set(kind, ok);}- return filterOk;+ return ok;}+/** Whether this browser's canvas takes a CSS filter (blur); where it can't, scenes keep their scale moves only. */+const canFilter = (ctx: Ctx): boolean => canvasFilters(ctx);+function makeCanvas(w: number, h: number): AnyCanvas {if (typeof OffscreenCanvas !== "undefined") return new OffscreenCanvas(w, h);return Object.assign(document.createElement("canvas"), { width: w, height: h });@@ -263,6 +287,20 @@ function drawNode(ctx: Ctx, n: DisplayNode, m: Matrix, alpha: number, src: Sourcctx.direction = "ltr";return;}+ case "video": {+ const v = src.clips?.get(n.src);+ if (!v) return;+ setMatrix(ctx, m);+ ctx.globalAlpha = alpha * (n.opacity ?? 1);+ ctx.imageSmoothingEnabled = true;+ ctx.imageSmoothingQuality = "high";+ try {+ ctx.drawImage(v, n.x, n.y, n.w, n.h);+ } catch {+ // A clip with no picture yet draws nothing (the ground shows).+ }+ return;+ }case "image": {const img = src.images.get(n.src);if (!img) return;@@ -280,7 +318,7 @@ function drawNode(ctx: Ctx, n: DisplayNode, m: Matrix, alpha: number, src: Sourc* Draw a display list onto a canvas `pixelWidth / list.w` times its design size (the canvas is that size). Clears to* the list's background first, so every frame stands alone.*/-export function drawDisplayList(ctx: Ctx, list: DisplayList, sources: Sources): void {+export function drawDisplayList(ctx: Ctx, list: DisplayList, sources: Sources, o: { finish?: boolean; grain?: boolean } = {}): void {const W = ctx.canvas.width;const H = ctx.canvas.height;const k = W / list.w;@@ -294,6 +332,79 @@ export function drawDisplayList(ctx: Ctx, list: DisplayList, sources: Sources):const base: Matrix = multiply([k, 0, 0, H / list.h, 0, 0], IDENTITY);for (const n of list.nodes) drawNode(ctx, n, base, 1, sources, 0);ctx.restore();+ if (list.finish && o.finish !== false) applyFinish(ctx, list.finish, { grain: o.grain });+}++// ---------------------------------------------------------------------------+// The finish (Kinetic's grade and grain), once per output frame++/** Whether this canvas draws contrast/saturate through a CSS filter (a pixel test per kind of canvas, done once). */+export function canGradeWithFilter(ctx: Ctx): boolean {+ return canvasFilters(ctx);+}++const grainCanvases = new Map<number, AnyCanvas>();+function grainCanvas(seed: number): AnyCanvas {+ let c = grainCanvases.get(seed);+ if (!c) {+ c = makeCanvas(GRAIN_TILE, GRAIN_TILE);+ const g = c.getContext("2d") as Ctx;+ const img = g.createImageData(GRAIN_TILE, GRAIN_TILE);+ const tile = grainTile(seed);+ for (let i = 0; i < tile.length; i++) {+ img.data[i * 4] = img.data[i * 4 + 1] = img.data[i * 4 + 2] = tile[i];+ img.data[i * 4 + 3] = 255;+ }+ g.putImageData(img, 0, 0);+ if (grainCanvases.size > 4) grainCanvases.clear();+ grainCanvases.set(seed, c);+ }+ return c;+}++/**+ * The finish over what is on the canvas: contrast and saturation (a canvas filter where the browser has one, else the+ * same maths per pixel), then the seeded grain laid with "overlay", sized to the canvas and offset per frame.+ * `pixels` forces the pixel pass (tests compare the two).+ */+export function applyFinish(ctx: Ctx, f: Finish, o: { grain?: boolean; pixels?: boolean } = {}): void {+ const W = ctx.canvas.width;+ const H = ctx.canvas.height;+ ctx.save();+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.globalAlpha = 1;+ if (f.contrast !== 0 || f.saturation !== 0) {+ if (!o.pixels && canGradeWithFilter(ctx)) {+ const layer = layerFor(ctx.canvas as AnyCanvas, 7);+ layer.ctx.save();+ layer.ctx.setTransform(1, 0, 0, 1, 0, 0);+ layer.ctx.globalCompositeOperation = "copy";+ layer.ctx.filter = "none";+ layer.ctx.drawImage(ctx.canvas, 0, 0);+ layer.ctx.restore();+ ctx.globalCompositeOperation = "copy";+ ctx.filter = cssFilter(f);+ ctx.drawImage(layer.canvas, 0, 0);+ ctx.filter = "none";+ } else {+ const img = ctx.getImageData(0, 0, W, H);+ gradePixels(img.data, f);+ ctx.putImageData(img, 0, 0);+ }+ }+ if (f.grain > 0 && o.grain !== false) {+ const pat = ctx.createPattern(grainCanvas(f.seed), "repeat");+ if (pat) {+ const s = grainScale(f, Math.min(W, H));+ const [ox, oy] = grainOffset(f.seed, f.frame);+ pat.setTransform(new DOMMatrix([s, 0, 0, s, -ox * s, -oy * s]));+ ctx.globalCompositeOperation = "overlay";+ ctx.globalAlpha = Math.min(1, f.grain * GRAIN_GAIN);+ ctx.fillStyle = pat;+ ctx.fillRect(0, 0, W, H);+ }+ }+ ctx.restore();}// ---------------------------------------------------------------------------diff --git a/src/components/motion/player.tsx b/src/components/motion/player.tsxindex 5076dfd0..5f24ced4 100644--- a/src/components/motion/player.tsx+++ b/src/components/motion/player.tsx@@ -169,7 +169,7 @@ export function MotionPlayer({ plan, sources, size, duration, fps, label, contro// Still frames: the rest frame (not playing, reduced motion, a chip at rest) or the scrubbed time.useEffect(() => {if (moving || !plan) return;- const t = !active ? (poster ?? plan.rest) : reduced && !askedPlay ? plan.rest : timeRef.current;+ const t = !active || (reduced && !askedPlay) ? (poster ?? plan.rest) : timeRef.current;draw(t);// eslint-disable-next-line react-hooks/exhaustive-deps}, [moving, plan, active, reduced, askedPlay, sources, time, poster]);diff --git a/src/components/motion/render.ts b/src/components/motion/render.tsindex 25fbc45b..f46100e1 100644--- a/src/components/motion/render.ts+++ b/src/components/motion/render.ts@@ -1,13 +1,13 @@"use client";import { avcCodec, encodeMp4, encodeVp8, pathVideoType, recordWithMediaRecorder, vp8Supported } from "@/components/cinema/video-encode";-import { listTravel, type DisplayList } from "@/lib/motion/display";+import { listTravel, videoNodeOf, type DisplayList } from "@/lib/motion/display";import type { Measure } from "@/lib/motion/layout";import type { Recipe } from "@/lib/motion/recipe";import type { LogoInfo, Outline, Scene, ScenePlan } from "@/lib/motion/scene";import { exportBitrate, exportSize } from "@/lib/motion/sizes";import { frameCount } from "@/lib/motion/time";-import { drawDisplayList, type Sources } from "./draw";+import { applyFinish, drawDisplayList, type Sources } from "./draw";/*** A Kinetic Motion clip rendered in the browser, frame-exact: frame i is the scene at t = i / fps, drawn at the export@@ -35,6 +35,10 @@ export interface RenderOptions {formats?: ("mp4" | "webm")[];/** Allow the real-time recorder when WebCodecs can't (it may drop a frame). */recorder?: boolean;+ /** The person's clips by key, with their size and length (Kinetic's video layer). */+ clips?: Record<string, { w: number; h: number; duration: number }>;+ /** Puts every clip on the picture a frame shows, before the frame is drawn (exact seeks). */+ prepare?: (list: DisplayList) => Promise<void>;}export interface RenderResult {@@ -95,17 +99,25 @@ export function blurSamples(travel: number, base: number): number {export function drawFrame(plan: ScenePlan, t: number, target: AnyCanvas, scratch: AnyCanvas, sources: Sources, o: { fps: number; samples: number; shutter: number; duration: number }): void {const tc = ctx2d(target);const half = o.shutter / 360 / o.fps / 2;+ const at = plan.evaluate(t);if (o.samples <= 1 || (plan.still(t - half) && plan.still(t))) {- drawDisplayList(tc, plan.evaluate(t), sources);+ drawDisplayList(tc, at, sources);return;}+ drawBlurred(plan, t, at, tc, scratch, sources, o);+ // The grade and grain once per output frame, after the blur (never blended across moments).+ if (at.finish) applyFinish(tc, at.finish);+}++function drawBlurred(plan: ScenePlan, t: number, at: DisplayList, tc: Ctx, scratch: AnyCanvas, sources: Sources, o: { fps: number; samples: number; shutter: number; duration: number }): void {+ const plain = { finish: false };// As many moments as this frame's motion needs, measured across the open shutter.const ends = shutterSamples(t, o.fps, 2, o.shutter, o.duration, plan.cuts);const first = plan.evaluate(ends[0].t);- const travel = listTravel(first, plan.evaluate(ends[1].t)) * (target.width / first.w);+ const travel = listTravel(first, plan.evaluate(ends[1].t)) * (tc.canvas.width / first.w);const samples = blurSamples(travel, o.samples);if (samples <= 1) {- drawDisplayList(tc, plan.evaluate(t), sources);+ drawDisplayList(tc, at, sources, plain);return;}const sc = ctx2d(scratch);@@ -114,10 +126,10 @@ export function drawFrame(plan: ScenePlan, t: number, target: AnyCanvas, scratchconst list: DisplayList = plan.evaluate(s.t);total += s.w;if (total === s.w) {- drawDisplayList(tc, list, sources);+ drawDisplayList(tc, list, sources, plain);continue;}- drawDisplayList(sc, list, sources);+ drawDisplayList(sc, list, sources, plain);tc.save();tc.setTransform(1, 0, 0, 1, 0, 0);tc.globalCompositeOperation = "source-over";@@ -127,20 +139,40 @@ export function drawFrame(plan: ScenePlan, t: number, target: AnyCanvas, scratch}}-/** Renders the whole clip (see the file's comment). Throws SHORTEN_MESSAGE when a typed field doesn't fit. */-export async function renderClip(scene: Scene, recipe: Recipe, o: RenderOptions): Promise<RenderResult> {- const plan = scene.plan({ recipe, measure: o.measure, logo: o.logo, images: o.images, outlines: o.outlines });+/** The plan a render draws (its typed words checked first). */+function planFor(scene: Scene, recipe: Recipe, o: Pick<RenderOptions, "measure" | "logo" | "images" | "outlines" | "clips">): ScenePlan {+ const plan = scene.plan({ recipe, measure: o.measure, logo: o.logo, images: o.images, outlines: o.outlines, clips: o.clips });if (plan.overflow.length) throw new Error(SHORTEN_MESSAGE);+ return plan;+}++/** Puts the clips on the picture frame `t` shows (when its list has one) before it is drawn. */+async function prepared(plan: ScenePlan, t: number, o: Pick<RenderOptions, "prepare">): Promise<void> {+ if (!o.prepare) return;+ const list = plan.evaluate(t);+ if (videoNodeOf(list)) await o.prepare(list);+}++/** The export's pixels, with even sides (H.264 wants them). */+function evenSize(recipe: Recipe): { W: number; H: number } {const { w, h } = exportSize(recipe.size);- // H.264 wants even sides.- const W = w - (w % 2);- const H = h - (h % 2);+ return { W: w - (w % 2), H: h - (h % 2) };+}++const stopped = () => new DOMException("The render was stopped", "AbortError");++/** Renders the whole clip (see the file's comment). Throws SHORTEN_MESSAGE when a typed field doesn't fit. */+export async function renderClip(scene: Scene, recipe: Recipe, o: RenderOptions): Promise<RenderResult> {+ const plan = planFor(scene, recipe, o);+ const { W, H } = evenSize(recipe);const n = frameCount(recipe.duration, recipe.fps);- const bitrate = recipe.export.bitrate ?? exportBitrate(recipe.size, recipe.duration);+ const bitrate = recipe.export.bitrate ?? exportBitrate(recipe.size, recipe.duration, { fps: recipe.fps, quality: recipe.export.quality });const target = canvas(W, H);const scratch = canvas(W, H);const opts = { fps: recipe.fps, samples: recipe.export.blurSamples, shutter: recipe.export.shutter, duration: recipe.duration };- const frame = (i: number) => {+ const frame = async (i: number) => {+ if (o.signal?.aborted) throw stopped();+ await prepared(plan, i / recipe.fps, o);drawFrame(plan, i / recipe.fps, target, scratch, o.sources, opts);o.onProgress?.(i + 1, n, target);return target;@@ -159,7 +191,7 @@ export async function renderClip(scene: Scene, recipe: Recipe, o: RenderOptions)break;}if (f === "webm" && (await vp8Supported(W, H, recipe.fps))) {- const [bytes] = await encodeVp8(n, W, H, recipe.fps, 1, (i) => [frame(i)], { bitrate, signal: o.signal });+ const [bytes] = await encodeVp8(n, W, H, recipe.fps, 1, async (i) => [await frame(i)], { bitrate, signal: o.signal });blob = new Blob([bytes as BlobPart], { type: "video/webm" });type = "video/webm";break;@@ -168,9 +200,11 @@ export async function renderClip(scene: Scene, recipe: Recipe, o: RenderOptions)if (!blob && o.recorder) {const rec = pathVideoType();if (rec) {+ // The real-time recorder draws in step with its own clock (it never waits for a seek).const [b] = await recordWithMediaRecorder(rec, n, W, H, recipe.fps, 1, (i) => {- const c = frame(i);- return [ctx2d(c).getImageData(0, 0, W, H)];+ drawFrame(plan, i / recipe.fps, target, scratch, o.sources, opts);+ o.onProgress?.(i + 1, n, target);+ return [ctx2d(target).getImageData(0, 0, W, H)];});blob = b;type = rec.split(";")[0];@@ -178,11 +212,69 @@ export async function renderClip(scene: Scene, recipe: Recipe, o: RenderOptions)}}if (!blob) throw new Error(NO_ENCODER_MESSAGE);- if (o.signal?.aborted) throw new DOMException("The render was stopped", "AbortError");+ if (o.signal?.aborted) throw stopped();+ await prepared(plan, plan.rest, o);drawDisplayList(ctx2d(target), plan.evaluate(plan.rest), o.sources);const poster = await toPng(target);return { blob, type, frames: n, poster, width: W, height: H, encoder };}+export interface PictureResult {+ blob: Blob;+ width: number;+ height: number;+}++const blurOf = (recipe: Recipe) => ({ fps: recipe.fps, samples: recipe.export.blurSamples, shutter: recipe.export.shutter, duration: recipe.duration });++/** One moment at the export size, with motion blur and the finish: a Frame PNG. */+export async function renderFrame(scene: Scene, recipe: Recipe, t: number, o: RenderOptions): Promise<PictureResult> {+ const plan = planFor(scene, recipe, o);+ const { W, H } = evenSize(recipe);+ const target = canvas(W, H);+ const at = Math.min(plan.rest, Math.max(0, t));+ await prepared(plan, at, o);+ drawFrame(plan, at, target, canvas(W, H), o.sources, blurOf(recipe));+ return { blob: await toPng(target), width: W, height: H };+}++/** The times a contact sheet shows: 9 frames at i / 8 of the way to the last frame. */+export const sheetTimes = (rest: number): number[] => Array.from({ length: 9 }, (_, i) => (i / 8) * rest);++/** A 3 × 3 contact sheet at the export size (each frame a third of it, no gutters), with blur and the finish. */+export async function renderSheet(scene: Scene, recipe: Recipe, o: RenderOptions): Promise<PictureResult> {+ const plan = planFor(scene, recipe, o);+ const { W, H } = evenSize(recipe);+ const cw = Math.floor(W / 3);+ const ch = Math.floor(H / 3);+ const sheet = canvas(W, H);+ const sc = ctx2d(sheet);+ sc.fillStyle = "#000";+ sc.fillRect(0, 0, W, H);+ const cell = canvas(cw, ch);+ const scratch = canvas(cw, ch);+ const times = sheetTimes(plan.rest);+ for (let i = 0; i < times.length; i++) {+ if (o.signal?.aborted) throw stopped();+ await prepared(plan, times[i], o);+ drawFrame(plan, times[i], cell, scratch, o.sources, blurOf(recipe));+ sc.drawImage(cell, (i % 3) * cw, Math.floor(i / 3) * ch);+ o.onProgress?.(i + 1, times.length, sheet);+ }+ return { blob: await toPng(sheet), width: W, height: H };+}++/** A version's picture: the rest frame, `long` pixels on its long side. */+export async function renderRest(scene: Scene, recipe: Recipe, o: RenderOptions, long = 540): Promise<PictureResult> {+ const plan = planFor(scene, recipe, o);+ const k = long / Math.max(plan.design.w, plan.design.h);+ const w = Math.max(2, Math.round(plan.design.w * k));+ const h = Math.max(2, Math.round(plan.design.h * k));+ const target = canvas(w, h);+ await prepared(plan, plan.rest, o);+ drawDisplayList(ctx2d(target), plan.evaluate(plan.rest), o.sources);+ return { blob: await toPng(target), width: w, height: h };+}+/** Whether this browser can encode an MP4 of this size (the cloud end card needs one). */export const canMakeMp4 = (w: number, h: number, fps: number) => avcCodec(w - (w % 2), h - (h % 2), fps).then((c) => !!c);diff --git a/src/components/motion/save.ts b/src/components/motion/save.tsindex 248a40a5..d5ae0e6d 100644--- a/src/components/motion/save.ts+++ b/src/components/motion/save.ts@@ -37,14 +37,15 @@ export interface SaveMeta {images?: string[];}-/** Uploads a rendered clip and records it as a result; returns the result. */-export async function saveMotionResult(clip: MotionResult, meta: SaveMeta): Promise<Generation> {- const ext = clip.type === "video/webm" ? "webm" : "mp4";- const [asset, poster] = await Promise.all([- uploadKinetic(new File([clip.blob], `kinetic-motion.${ext}`, { type: clip.type })),- clip.poster ? uploadKinetic(new File([clip.poster], "kinetic-motion.png", { type: "image/png" })).catch(() => null) : null,- ]);+/** The files a result names as its inputs: its pictures (logo, product) and the clip under its words. */+function inputsOf(meta: SaveMeta): { images?: string[]; video?: string } {const images = (meta.images ?? []).filter((u) => u.startsWith("/api/files/")).slice(0, 4);+ const video = meta.recipe.layers?.video?.src;+ return { ...(images.length && { images }), ...(video && { video }) };+}++/** Records an uploaded Kinetic file as a result (a clip, or a frame, sheet or version picture). */+async function record(meta: SaveMeta, output: { url: string; kind: "video" | "image"; contentType: string; meta?: { poster: string } }): Promise<Generation> {const res = await fetch("/api/generations/local", {method: "POST",headers: { "Content-Type": "application/json" },@@ -54,9 +55,9 @@ export async function saveMotionResult(clip: MotionResult, meta: SaveMeta): Promop: "motion",prompt: meta.prompt.slice(0, 2000),title: meta.title.slice(0, 200),- inputs: images.length ? { images } : {},+ inputs: inputsOf(meta),params: { extra: { motion: meta.recipe } },- output: { url: asset.url, kind: "video", contentType: asset.contentType, ...(poster && { meta: { poster: poster.url } }) },+ output,}),});const body = (await res.json().catch(() => ({}))) as Generation & { error?: string };@@ -64,6 +65,22 @@ export async function saveMotionResult(clip: MotionResult, meta: SaveMeta): Promreturn body;}+/** Uploads a rendered picture (a PNG frame, contact sheet or version) and records it as a result. */+export async function saveMotionPicture(png: Blob, meta: SaveMeta): Promise<Generation> {+ const asset = await uploadKinetic(new File([png], "kinetic-motion.png", { type: "image/png" }));+ return record(meta, { url: asset.url, kind: "image", contentType: "image/png" });+}++/** Uploads a rendered clip and records it as a result; returns the result. */+export async function saveMotionResult(clip: MotionResult, meta: SaveMeta): Promise<Generation> {+ const ext = clip.type === "video/webm" ? "webm" : "mp4";+ const [asset, poster] = await Promise.all([+ uploadKinetic(new File([clip.blob], `kinetic-motion.${ext}`, { type: clip.type })),+ clip.poster ? uploadKinetic(new File([clip.poster], "kinetic-motion.png", { type: "image/png" })).catch(() => null) : null,+ ]);+ return record(meta, { url: asset.url, kind: "video", contentType: asset.contentType ?? clip.type, ...(poster && { meta: { poster: poster.url } }) });+}+export type SavePhase = { kind: "idle" } | { kind: "rendering"; done: number; total: number } | { kind: "saving" } | { kind: "saved"; id: string };/**diff --git a/src/components/preset-icons.ts b/src/components/preset-icons.tsindex 497f4ae8..7aae82c0 100644--- a/src/components/preset-icons.ts+++ b/src/components/preset-icons.ts@@ -1,4 +1,4 @@// Generated by scripts/gen-icon-map.mjs — do not edit by hand.-import { Activity, Angry, Aperture, AppWindow, ArrowDown, ArrowDownToDot, ArrowDownToLine, ArrowLeft, ArrowLeftRight, ArrowLeftToLine, ArrowRight, ArrowRightLeft, ArrowRightToLine, ArrowUp, ArrowUpFromLine, ArrowUpRight, ArrowUpWideNarrow, AtSign, Atom, AudioLines, AudioWaveform, Axis3d, BadgeDollarSign, Banana, Banknote, Bath, Bike, Binary, Biohazard, Bird, Blocks, Bomb, BookOpen, Bot, Box, Boxes, BriefcaseBusiness, Brush, Bug, Building, Building2, Cake, Camera, Candy, Car, CarFront, Castle, ChevronDown, ChevronUp, ChevronsDown, ChevronsLeft, ChevronsRight, ChevronsUp, Circle, CircleDashed, CircleDot, Citrus, Clapperboard, Clock, Cloud, CloudFog, CloudLightning, CloudRain, Cloudy, Coffee, Cog, Columns3, Combine, Contrast, Copy, Cpu, Crosshair, Crown, CupSoda, Diamond, Disc, Disc3, Dog, Drama, Droplet, Droplets, Dumbbell, Ear, Earth, Eraser, Expand, Eye, EyeOff, FastForward, Feather, FerrisWheel, FileImage, FileText, Film, Fingerprint, Fish, Flame, FlaskConical, Flower, Flower2, Focus, Footprints, Frame, Frown, GalleryHorizontal, Gamepad2, Gauge, Gem, Ghost, GitBranch, Glasses, Globe, Globe2, Grid2x2, Grid3x3, Grip, Hammer, Hand, Headphones, Heart, HeartHandshake, Hexagon, History, Hourglass, House, Image, ImageIcon, Images, Infinity, Joystick, Lamp, Landmark, Languages, Laugh, Layers, LayoutDashboard, LayoutGrid, Leaf, Lightbulb, Link, Maximize, Maximize2, Megaphone, MessageCircle, MessageSquareText, Mic, Mic2, MicVocal, Microscope, Monitor, MonitorPlay, Moon, Mountain, MountainSnow, MousePointerClick, MoveDiagonal, MoveDiagonal2, MoveHorizontal, Music, Newspaper, Orbit, Package, PackageOpen, PackagePlus, Paintbrush, Palette, Palmtree, PanelTop, PartyPopper, Pause, PawPrint, PenLine, PenTool, Pencil, PencilRuler, PersonStanding, Pizza, Plane, Pointer, Presentation, Rabbit, Radar, Rainbow, Redo2, RefreshCw, Refrigerator, Repeat, Repeat2, Rocket, Rotate3d, RotateCcw, RotateCw, Rows2, Sailboat, Scaling, ScanEye, ScanFace, ScanLine, Scissors, Search, Send, Shapes, Shell, Shield, ShieldCheck, Shirt, Shuffle, Signpost, Skull, SlidersHorizontal, Smartphone, Smile, SmilePlus, Snail, Snowflake, Sparkle, Sparkles, Spline, SprayCan, Sprout, Square, SquareDashed, Star, Sticker, StickyNote, Store, Sun, SunDim, Sunrise, Sunset, Swords, Table, Thermometer, ThumbsUp, Ticket, Timer, Tornado, TrainFront, TrendingUp, Trophy, Truck, Tv, Type, Undo2, Unplug, User, UserRound, UserRoundCog, UserX, Users, Utensils, UtensilsCrossed, Video, Volleyball, Wand, Wand2, Waves, Waypoints, Wind, Wine, Worm, Zap, ZoomIn, ZoomOut, type LucideIcon } from "lucide-react";+import { Activity, Angry, Aperture, AppWindow, ArrowDown, ArrowDownToDot, ArrowDownToLine, ArrowLeft, ArrowLeftRight, ArrowLeftToLine, ArrowRight, ArrowRightLeft, ArrowRightToLine, ArrowUp, ArrowUpFromLine, ArrowUpRight, ArrowUpWideNarrow, AtSign, Atom, AudioLines, AudioWaveform, Axis3d, BadgeDollarSign, Banana, Banknote, Bath, Bike, Binary, Biohazard, Bird, Blocks, Bomb, BookOpen, Bot, Box, Boxes, BriefcaseBusiness, Brush, Bug, Building, Building2, Cake, Camera, Candy, Car, CarFront, Castle, ChevronDown, ChevronUp, ChevronsDown, ChevronsLeft, ChevronsRight, ChevronsUp, Circle, CircleDashed, CircleDot, Citrus, Clapperboard, Clock, Cloud, CloudFog, CloudLightning, CloudRain, Cloudy, Coffee, Cog, Columns3, Combine, Contrast, Copy, Cpu, Crosshair, Crown, CupSoda, Diamond, Disc, Disc3, Dog, Drama, Droplet, Droplets, Dumbbell, Ear, Earth, Eraser, Expand, Eye, EyeOff, FastForward, Feather, FerrisWheel, FileImage, FileText, Film, Fingerprint, Fish, Flame, FlaskConical, Flower, Flower2, Focus, Footprints, Frame, Frown, GalleryHorizontal, Gamepad2, Gauge, Gem, Ghost, GitBranch, Glasses, Globe, Globe2, Grid2x2, Grid3x3, Grip, Hammer, Hand, Headphones, Heart, HeartHandshake, Hexagon, History, Hourglass, House, Image, ImageIcon, Images, Infinity, Joystick, Lamp, Landmark, Languages, Laugh, Layers, LayoutDashboard, LayoutGrid, Leaf, LetterText, Lightbulb, Link, Maximize, Maximize2, Megaphone, MessageCircle, MessageSquareText, Mic, Mic2, MicVocal, Microscope, Monitor, MonitorPlay, Moon, Mountain, MountainSnow, MousePointerClick, MoveDiagonal, MoveDiagonal2, MoveHorizontal, Music, Newspaper, Orbit, Package, PackageOpen, PackagePlus, Paintbrush, Palette, Palmtree, PanelTop, PartyPopper, Pause, PawPrint, PenLine, PenTool, Pencil, PencilRuler, PersonStanding, Pizza, Plane, Pointer, Presentation, Rabbit, Radar, Rainbow, Redo2, RefreshCw, Refrigerator, Repeat, Repeat2, Rocket, Rotate3d, RotateCcw, RotateCw, Rows2, Sailboat, Scaling, ScanEye, ScanFace, ScanLine, Scissors, Search, Send, Shapes, Shell, Shield, ShieldCheck, Shirt, Shuffle, Signpost, Skull, SlidersHorizontal, Smartphone, Smile, SmilePlus, Snail, Snowflake, Sparkle, Sparkles, Spline, SprayCan, Sprout, Square, SquareDashed, Star, Sticker, StickyNote, Store, Sun, SunDim, Sunrise, Sunset, Swords, Table, Thermometer, ThumbsUp, Ticket, Timer, Tornado, TrainFront, TrendingUp, Trophy, Truck, Tv, Type, Undo2, Unplug, User, UserRound, UserRoundCog, UserX, Users, Utensils, UtensilsCrossed, Video, Volleyball, Wand, Wand2, Waves, Waypoints, Wind, Wine, Worm, Zap, ZoomIn, ZoomOut, type LucideIcon } from "lucide-react";-export const PRESET_ICONS: Record<string, LucideIcon> = { Activity, Angry, Aperture, AppWindow, ArrowDown, ArrowDownToDot, ArrowDownToLine, ArrowLeft, ArrowLeftRight, ArrowLeftToLine, ArrowRight, ArrowRightLeft, ArrowRightToLine, ArrowUp, ArrowUpFromLine, ArrowUpRight, ArrowUpWideNarrow, AtSign, Atom, AudioLines, AudioWaveform, Axis3d, BadgeDollarSign, Banana, Banknote, Bath, Bike, Binary, Biohazard, Bird, Blocks, Bomb, BookOpen, Bot, Box, Boxes, BriefcaseBusiness, Brush, Bug, Building, Building2, Cake, Camera, Candy, Car, CarFront, Castle, ChevronDown, ChevronUp, ChevronsDown, ChevronsLeft, ChevronsRight, ChevronsUp, Circle, CircleDashed, CircleDot, Citrus, Clapperboard, Clock, Cloud, CloudFog, CloudLightning, CloudRain, Cloudy, Coffee, Cog, Columns3, Combine, Contrast, Copy, Cpu, Crosshair, Crown, CupSoda, Diamond, Disc, Disc3, Dog, Drama, Droplet, Droplets, Dumbbell, Ear, Earth, Eraser, Expand, Eye, EyeOff, FastForward, Feather, FerrisWheel, FileImage, FileText, Film, Fingerprint, Fish, Flame, FlaskConical, Flower, Flower2, Focus, Footprints, Frame, Frown, GalleryHorizontal, Gamepad2, Gauge, Gem, Ghost, GitBranch, Glasses, Globe, Globe2, Grid2x2, Grid3x3, Grip, Hammer, Hand, Headphones, Heart, HeartHandshake, Hexagon, History, Hourglass, House, Image, ImageIcon, Images, Infinity, Joystick, Lamp, Landmark, Languages, Laugh, Layers, LayoutDashboard, LayoutGrid, Leaf, Lightbulb, Link, Maximize, Maximize2, Megaphone, MessageCircle, MessageSquareText, Mic, Mic2, MicVocal, Microscope, Monitor, MonitorPlay, Moon, Mountain, MountainSnow, MousePointerClick, MoveDiagonal, MoveDiagonal2, MoveHorizontal, Music, Newspaper, Orbit, Package, PackageOpen, PackagePlus, Paintbrush, Palette, Palmtree, PanelTop, PartyPopper, Pause, PawPrint, PenLine, PenTool, Pencil, PencilRuler, PersonStanding, Pizza, Plane, Pointer, Presentation, Rabbit, Radar, Rainbow, Redo2, RefreshCw, Refrigerator, Repeat, Repeat2, Rocket, Rotate3d, RotateCcw, RotateCw, Rows2, Sailboat, Scaling, ScanEye, ScanFace, ScanLine, Scissors, Search, Send, Shapes, Shell, Shield, ShieldCheck, Shirt, Shuffle, Signpost, Skull, SlidersHorizontal, Smartphone, Smile, SmilePlus, Snail, Snowflake, Sparkle, Sparkles, Spline, SprayCan, Sprout, Square, SquareDashed, Star, Sticker, StickyNote, Store, Sun, SunDim, Sunrise, Sunset, Swords, Table, Thermometer, ThumbsUp, Ticket, Timer, Tornado, TrainFront, TrendingUp, Trophy, Truck, Tv, Type, Undo2, Unplug, User, UserRound, UserRoundCog, UserX, Users, Utensils, UtensilsCrossed, Video, Volleyball, Wand, Wand2, Waves, Waypoints, Wind, Wine, Worm, Zap, ZoomIn, ZoomOut };+export const PRESET_ICONS: Record<string, LucideIcon> = { Activity, Angry, Aperture, AppWindow, ArrowDown, ArrowDownToDot, ArrowDownToLine, ArrowLeft, ArrowLeftRight, ArrowLeftToLine, ArrowRight, ArrowRightLeft, ArrowRightToLine, ArrowUp, ArrowUpFromLine, ArrowUpRight, ArrowUpWideNarrow, AtSign, Atom, AudioLines, AudioWaveform, Axis3d, BadgeDollarSign, Banana, Banknote, Bath, Bike, Binary, Biohazard, Bird, Blocks, Bomb, BookOpen, Bot, Box, Boxes, BriefcaseBusiness, Brush, Bug, Building, Building2, Cake, Camera, Candy, Car, CarFront, Castle, ChevronDown, ChevronUp, ChevronsDown, ChevronsLeft, ChevronsRight, ChevronsUp, Circle, CircleDashed, CircleDot, Citrus, Clapperboard, Clock, Cloud, CloudFog, CloudLightning, CloudRain, Cloudy, Coffee, Cog, Columns3, Combine, Contrast, Copy, Cpu, Crosshair, Crown, CupSoda, Diamond, Disc, Disc3, Dog, Drama, Droplet, Droplets, Dumbbell, Ear, Earth, Eraser, Expand, Eye, EyeOff, FastForward, Feather, FerrisWheel, FileImage, FileText, Film, Fingerprint, Fish, Flame, FlaskConical, Flower, Flower2, Focus, Footprints, Frame, Frown, GalleryHorizontal, Gamepad2, Gauge, Gem, Ghost, GitBranch, Glasses, Globe, Globe2, Grid2x2, Grid3x3, Grip, Hammer, Hand, Headphones, Heart, HeartHandshake, Hexagon, History, Hourglass, House, Image, ImageIcon, Images, Infinity, Joystick, Lamp, Landmark, Languages, Laugh, Layers, LayoutDashboard, LayoutGrid, Leaf, LetterText, Lightbulb, Link, Maximize, Maximize2, Megaphone, MessageCircle, MessageSquareText, Mic, Mic2, MicVocal, Microscope, Monitor, MonitorPlay, Moon, Mountain, MountainSnow, MousePointerClick, MoveDiagonal, MoveDiagonal2, MoveHorizontal, Music, Newspaper, Orbit, Package, PackageOpen, PackagePlus, Paintbrush, Palette, Palmtree, PanelTop, PartyPopper, Pause, PawPrint, PenLine, PenTool, Pencil, PencilRuler, PersonStanding, Pizza, Plane, Pointer, Presentation, Rabbit, Radar, Rainbow, Redo2, RefreshCw, Refrigerator, Repeat, Repeat2, Rocket, Rotate3d, RotateCcw, RotateCw, Rows2, Sailboat, Scaling, ScanEye, ScanFace, ScanLine, Scissors, Search, Send, Shapes, Shell, Shield, ShieldCheck, Shirt, Shuffle, Signpost, Skull, SlidersHorizontal, Smartphone, Smile, SmilePlus, Snail, Snowflake, Sparkle, Sparkles, Spline, SprayCan, Sprout, Square, SquareDashed, Star, Sticker, StickyNote, Store, Sun, SunDim, Sunrise, Sunset, Swords, Table, Thermometer, ThumbsUp, Ticket, Timer, Tornado, TrainFront, TrendingUp, Trophy, Truck, Tv, Type, Undo2, Unplug, User, UserRound, UserRoundCog, UserX, Users, Utensils, UtensilsCrossed, Video, Volleyball, Wand, Wand2, Waves, Waypoints, Wind, Wine, Worm, Zap, ZoomIn, ZoomOut };diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsxindex 979fc8ae..ee2ae172 100644--- a/src/components/studio/result-actions.tsx+++ b/src/components/studio/result-actions.tsx@@ -2,6 +2,7 @@import {ArchiveRestore,+ LetterText,Disc3,Layers3,ListMusic,@@ -140,6 +141,7 @@ export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {"restore-video": Palette,"extend-song": ListMusic,"remix-song": Disc3,+ "remix-kinetic": LetterText,"song-stems": Layers3,"delete-forever": Trash2,};diff --git a/src/components/studio/viewer.tsx b/src/components/studio/viewer.tsxindex 676bb107..f0fb0c50 100644--- a/src/components/studio/viewer.tsx+++ b/src/components/studio/viewer.tsx@@ -75,7 +75,7 @@ function Details({ g, index }: { g: Generation; index: number }) {<div className="space-y-4"><div><p className="font-heading text-[20px] leading-snug">{title}</p>- {g.prompt && g.prompt !== title && <p className="mt-1 line-clamp-6 text-[12px] leading-relaxed break-words text-muted-foreground">Sent to the model: {g.prompt}</p>}+ {g.prompt && g.prompt !== title && <p className="mt-1 line-clamp-6 text-[12px] leading-relaxed break-words text-muted-foreground">{g.modelId === "local-motion" ? "Words" : "Sent to the model"}: {g.prompt}</p>}{g.prompt && (<buttononClick={() => void copyWithToast(g.prompt ?? "", "Prompt copied")}diff --git a/src/components/template-cover.tsx b/src/components/template-cover.tsxindex 28f494a2..5369b1bd 100644--- a/src/components/template-cover.tsx+++ b/src/components/template-cover.tsx@@ -2,17 +2,19 @@import { memo, useMemo } from "react";import { PresetPreview, usePreviewPlayback } from "@/components/preset-preview";+import type { AutoPlay } from "@/lib/preview-playback";import { NO_COVER, templatePreview, type CoverFrame, type TemplateCover } from "@/lib/template-covers";import { cn } from "@/lib/utils";/*** A template tile's playback, as the gallery cards': spread `handlers` on the card and give it `ref`. A clip plays by* itself while in view (a few at once, never with reduced motion or Save-Data), and on hover, focus or tap. A tile- * without a clip (a still, or its drawn art) never plays: the hooks run all the same.+ * without a clip (a still, or its drawn art) never plays: the hooks run all the same. With `auto: "touch"`, a clip plays+ * by itself only where nothing can hover (elsewhere on hover or focus).*/-export function useCoverPlayback<T extends HTMLElement>(key: string, cover: TemplateCover | undefined) {+export function useCoverPlayback<T extends HTMLElement>(key: string, cover: TemplateCover | undefined, o: { auto?: AutoPlay } = {}) {const preview = useMemo(() => (cover ? templatePreview(cover) : NO_COVER), [cover]);- return usePreviewPlayback<T>(`tpl:${key}`, preview);+ return usePreviewPlayback<T>(`tpl:${key}`, preview, { auto: o.auto });}/**diff --git a/src/lib/catalog/canvas.ts b/src/lib/catalog/canvas.tsindex 8e8f8066..443f7b6c 100644--- a/src/lib/catalog/canvas.ts+++ b/src/lib/catalog/canvas.ts@@ -24,6 +24,8 @@ import { fillLayout, layoutPlaceholders } from "@/lib/layout-surfaces";import { FLY_MODELS, flyKeys, planFlyAround } from "./fly-around";import type { CameraKey } from "@/lib/camera-path";import type { ExactOrbit } from "@/lib/exact-orbit";+import type { Recipe } from "@/lib/motion/recipe";+import { CLIP_SCENES as KINETIC_CLIP_SCENES } from "@/lib/motion/kinetic-groups";import {OPERATION_LABELS,OPERATION_OUTPUT,@@ -76,6 +78,7 @@ export type CanvasNodeType =| "layout"| "camera-path"| "fly-around"+ | "kinetic"| "output"| "note";@@ -133,6 +136,8 @@ export interface CanvasNodeData {keys?: CameraKey[];/** Fly around: the clip's length in seconds (the cloud; your GPU always films about 5 s). */duration?: number;+ /** Kinetic: the scene and its settings, as a Kinetic Motion recipe (its words come from the Text input per row). */+ kinetic?: Recipe;}export interface CanvasNode {@@ -216,7 +221,7 @@ export interface CanvasSummary {pageCount: number;templateId: string | null;/** The newest finished image or video made on this canvas. */- preview: { url: string; kind: MediaKind } | null;+ preview: { url: string; kind: MediaKind; poster?: string } | null;outline: Outline;createdAt: number;updatedAt: number;@@ -271,6 +276,7 @@ export const NODE_SPECS: Record<CanvasNodeType, NodeSpec> = {layout: { type: "layout", label: "Layout", group: "Inputs", icon: "LayoutDashboard", description: "Boxes for a headline, a product, a price: the image model draws each in its place" },"camera-path": { type: "camera-path", label: "Camera path", group: "Inputs", icon: "Orbit", description: "A move round the subject: a preset or an exact orbit" },"fly-around": { type: "fly-around", label: "Fly around", group: "Generate", icon: "Rotate3d", ops: ["camera-path"], description: "A still filmed along a camera path, with other views if you have them" },+ kinetic: { type: "kinetic", label: "Kinetic", group: "Generate", icon: "LetterText", description: "Your words as motion graphics in your brand, drawn in your browser" },output: { type: "output", label: "Output", group: "Output", icon: "MonitorPlay", description: "Preview what's connected, side by side" },note: { type: "note", label: "Sticky note", group: "Output", icon: "StickyNote", description: "A note on the board (not run)" },};@@ -328,6 +334,7 @@ export const PALETTE: PaletteItem[] = [{ ...pick("layout"), id: "layout", data: { layout: { summary: { caption: "", meta: [], canvas: "single" }, items: [], aspect: "1:1" } }, keywords: "layout boxes poster text placement composition headline price moss" },{ ...pick("camera-path"), id: "camera-path", data: { pathPreset: "orbit_360" }, keywords: "orbit arc camera move path keyframes exact turnaround" },{ ...pick("fly-around"), id: "fly-around", keywords: "orbit fly around turnaround camera path 360 spin product" },+ { ...pick("kinetic"), id: "kinetic", keywords: "motion text title animation brand kinetic" },{ ...pick("output"), id: "output", keywords: "preview compare result" },{ ...pick("note"), id: "note", keywords: "comment annotation" },];@@ -644,6 +651,13 @@ export function inputPorts(n: Pick<CanvasNode, "type" | "data">): PortDef[] {// Clone voice: the sample can come from another node (a recording, a generated voice) instead of a file.if (n.type === "clone-voice") return [{ id: "audio", label: "Sample", type: "audio", multiple: false }];if (n.type === "output") return [];+ // Kinetic: words (a Table feeds one render per row), a picture (the product, else the logo) and a clip under the words.+ if (n.type === "kinetic")+ return [+ { id: "prompt", label: "Text", type: "text", multiple: true },+ { id: "images", label: "Picture", type: "image", multiple: false },+ { id: "video", label: "Clip", type: "video", multiple: false },+ ];// Fly around: the still (then any other views of the subject), the path, and motion words.if (n.type === "fly-around")return [@@ -698,7 +712,7 @@ export function outputType(_graph: CanvasGraph, n: CanvasNode): PortType | nullif (n.type === "clone-voice") return "voice";if (n.type === "element") return "element";if (n.type === "camera-path") return "path";- if (n.type === "fly-around") return "video";+ if (n.type === "fly-around" || n.type === "kinetic") return "video";if (MEDIA_INPUT_TYPE[n.type]) return MEDIA_INPUT_TYPE[n.type]!;if (!isGenerator(n)) return null;// Never inferred from the inputs (that would walk the whole upstream graph): a chosen or fixed op, else the model's kind.@@ -817,6 +831,9 @@ export function connectionError(graph: CanvasGraph, c: Connection): string | nulif (s.id === t.id) return "A node can't feed itself";const type = outputType(graph, s);if (!type || (c.sourceHandle && !outputHandles(s).includes(c.sourceHandle))) return `${nodeLabel(s)} has no output`;+ // Kinetic renders in the browser: its clips go to Output nodes only (for now).+ if (s.type === "kinetic" && t.type !== "output") return "Connect Kinetic to an Output node";+ if (t.type === "kinetic" && c.targetHandle === "video" && !KINETIC_CLIP_SCENES.includes(t.data.kinetic?.scene ?? "")) return "This scene doesn't take a clip";if (t.type === "output") {if (c.targetHandle && c.targetHandle !== PREVIEW_IN) return "Unknown input";if (!acceptsType("preview", type)) return "Elements go into a model's Elements input";diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex 5f779add..d4f0ee60 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -137,6 +137,8 @@ const LIBRARY_CHANGES: [methods: string, path: RegExp][] = [],["DELETE", /^\/api\/(katana|marketing\/runs|photodump\/packs)\/[^/]+$/],["POST", /^\/api\/canvases\/[^/]+\/duplicate$/],+ // A Kinetic node's run (rendered in the owner's browser) kept on the canvas.+ ["PUT", /^\/api\/canvases\/[^/]+\/runs\/[^/]+$/],// A ready-made starter (a channel, a brand kit with its product) is saved to the owner's library.["POST", /^\/api\/starters\/[^/]+$/],["POST", /^\/api\/assist\/skills\/[^/]+\/duplicate$/],diff --git a/src/lib/motion/display.ts b/src/lib/motion/display.tsindex db34652d..9c4fc26c 100644--- a/src/lib/motion/display.ts+++ b/src/lib/motion/display.ts@@ -4,6 +4,8 @@* export and the covers alike. Coordinates are design units (1080 on the frame's short side); the drawer scales.*/+import type { Finish } from "./finish";+/** A 2D affine matrix [a, b, c, d, e, f] (canvas setTransform order). */export type Matrix = [number, number, number, number, number, number];@@ -148,7 +150,21 @@ export interface ImageNode {smoothing?: boolean;}-export type DisplayNode = GroupNode | RectNode | EllipseNode | PathNode | TextNode | ImageNode;+/** The person's own clip (Kinetic's video layer): the frame on screen at `time` seconds into the clip, in a box. */+export interface VideoNode {+ type: "video";+ /** The clip's key in the drawer's sources ("clip"). */+ src: string;+ x: number;+ y: number;+ w: number;+ h: number;+ /** Seconds into the clip. */+ time: number;+ opacity?: number;+}++export type DisplayNode = GroupNode | RectNode | EllipseNode | PathNode | TextNode | ImageNode | VideoNode;export interface DisplayList {/** Design size. */@@ -156,8 +172,13 @@ export interface DisplayList {h: number;background: string;nodes: DisplayNode[];+ /** A grade and grain over the finished frame (absent: as drawn). */+ finish?: Finish;}+/** The clip's node in a list (the video layer is always drawn first), if any. */+export const videoNodeOf = (list: DisplayList): VideoNode | undefined => (list.nodes[0]?.type === "video" ? list.nodes[0] : undefined);+export const group = (children: DisplayNode[], o: Omit<GroupNode, "type" | "children"> = {}): GroupNode => ({ type: "group", ...o, children });/** Every text node in a list, in drawing order (tests read the fields from it). */diff --git a/src/lib/motion/ease.ts b/src/lib/motion/ease.tsindex 09f05d3d..51175f6c 100644--- a/src/lib/motion/ease.ts+++ b/src/lib/motion/ease.ts@@ -178,3 +178,28 @@ export const CURVES = {export type CurveName = keyof typeof CURVES;export const curve = (name: CurveName): Ease => CURVES[name];++/**+ * The motion feels Kinetic's editor offers: each swaps a few of the named curves for its own version, and leaves the+ * rest as authored (move, exit, draw, drift and linear are never swapped, so in-place moves, exits, strokes and the+ * camera's rest keep their timing). Every swapped curve keeps f(0) = 0 and f(1) = 1.+ * smooth: the curves as designed. snappy: quicker, firmer arrivals. springy: springs with more overshoot (a pop about+ * 10 % past its size). steady: even sine in-and-out moves.+ */+export const CURVE_SETS: Record<"smooth" | "snappy" | "springy" | "steady", Partial<Record<CurveName, Ease>>> = {+ smooth: {},+ snappy: {+ enter: bezier(0.05, 0.9, 0.1, 1),+ glide: bezier(0.12, 0.9, 0.2, 1),+ settle: spring({ stiffness: 320, damping: 32 }),+ },+ springy: {+ enter: spring({ stiffness: 240, damping: 17 }),+ pop: spring({ stiffness: 380, damping: 23 }),+ settle: spring({ stiffness: 170, damping: 14.5 }),+ },+ steady: { enter: sine.inOut, glide: sine.inOut, settle: sine.inOut, pop: sine.inOut },+};++/** The curves a feel never swaps. */+export const FIXED_CURVES: readonly CurveName[] = ["move", "exit", "draw", "drift", "linear"];diff --git a/src/lib/motion/edit.ts b/src/lib/motion/edit.tsnew file mode 100644index 00000000..25cd6769--- /dev/null+++ b/src/lib/motion/edit.ts@@ -0,0 +1,463 @@+/**+ * Kinetic's editor on the timeline (pure): shot windows, motion groups and their retiming (a warp of each group's own+ * clock and a rate), the camera's clock, parameter tracks, the extra camera, and the presets. The two scene wrappers+ * (marketing/kit.ts and end-card/shared.ts) call it after building their timeline; a recipe without any of the editor's+ * fields comes out exactly as designed.+ *+ * A group edit never moves another group's events, the cuts, the typed words, the film's length or the last frame:+ * the rate scales a group's events about its first start and is held so the group still ends inside its shot and (where+ * the design allows) a second before the last frame.+ */++import { curve, CURVE_SETS, quad, cubic, sine, type CurveName, type Ease } from "./ease";+import { cameraGroupId, groupDefsFor, groupMatches, type MotionGroupDef } from "./kinetic-groups";+import { TRACK_LIMITS, type GroupTiming, type Recipe, type Track, type TrackId } from "./recipe";+import { local } from "./time";+import { sample, type MotionEvent } from "./tween";++// ---------------------------------------------------------------------------+// Shot windows and groups++export type Window = [number, number];++/** The shots between the plan's cuts: [0, c1), [c1, c2) … [cn, last]. */+export function shotWindows(plan: { cuts: readonly number[]; rest: number }): Window[] {+ const cuts = [...plan.cuts].filter((c) => c > 0 && c < plan.rest).sort((a, b) => a - b);+ const edges = [0, ...cuts, plan.rest];+ return edges.slice(0, -1).map((a, i) => [a, edges[i + 1]] as Window);+}++/** The window index a time falls in (the last window holds the last frame). */+export function windowAt(windows: readonly Window[], t: number): number {+ for (let i = 0; i < windows.length; i++) if (t < windows[i][1]) return i;+ return Math.max(0, windows.length - 1);+}++export interface MotionGroup {+ id: string;+ label: string;+ /** The shot it sits in (where its first event starts). */+ window: number;+ camera: boolean;+ events: MotionEvent[];+}++/**+ * A scene's groups on a timeline: the catalogue's groups that have events (in the shot where each starts), and a+ * Camera group in every shot (the scene's camera, its breath, the extra camera, and any camera-kind events).+ */+export function groupsOf(defs: readonly MotionGroupDef[], events: readonly MotionEvent[], windows: readonly Window[]): MotionGroup[] {+ const out: MotionGroup[] = [];+ for (const d of defs) {+ const evs = events.filter((e) => e.kind !== "camera" && groupMatches(defs, e).includes(d.id));+ if (!evs.length) continue;+ const g0 = Math.min(...evs.map((e) => e.start));+ out.push({ id: d.id, label: d.label, window: windowAt(windows, Math.max(0, g0)), camera: false, events: evs });+ }+ windows.forEach((_, w) => {+ const evs = events.filter((e) => e.kind === "camera" && windowAt(windows, Math.max(0, e.start)) === w);+ out.push({ id: cameraGroupId(w), label: "Camera", window: w, camera: true, events: evs });+ });+ return out;+}++// ---------------------------------------------------------------------------+// Warps++export type WarpKeys = [number, number][];+export const IDENTITY_KEYS: WarpKeys = [+ [0, 0],+ [1, 1],+];++/**+ * A group's warp: its keys joined by monotone cubic interpolation (Fritsch–Carlson), so it never runs backwards, with+ * warp(0) = 0 and warp(1) = 1 exactly. Two keys [0, 0] and [1, 1] give the plain identity.+ */+export function warpOf(keys: readonly (readonly [number, number])[]): (u: number) => number {+ const n = keys.length;+ if (n < 2 || (n === 2 && keys[0][1] === 0 && keys[1][1] === 1 && keys[0][0] === 0 && keys[1][0] === 1)) return (u) => (u <= 0 ? 0 : u >= 1 ? 1 : u);+ const x = keys.map((k) => k[0]);+ const y = keys.map((k) => k[1]);+ const d: number[] = [];+ for (let i = 0; i < n - 1; i++) d.push((y[i + 1] - y[i]) / Math.max(1e-9, x[i + 1] - x[i]));+ const m: number[] = new Array(n).fill(0);+ m[0] = d[0];+ m[n - 1] = d[n - 2];+ for (let i = 1; i < n - 1; i++) m[i] = d[i - 1] * d[i] <= 0 ? 0 : (d[i - 1] + d[i]) / 2;+ for (let i = 0; i < n - 1; i++) {+ if (d[i] === 0) {+ m[i] = 0;+ m[i + 1] = 0;+ continue;+ }+ const a = m[i] / d[i];+ const b = m[i + 1] / d[i];+ const s = a * a + b * b;+ if (s > 9) {+ const tau = 3 / Math.sqrt(s);+ m[i] = tau * a * d[i];+ m[i + 1] = tau * b * d[i];+ }+ }+ return (u) => {+ if (!(u > 0)) return 0;+ if (u >= 1) return 1;+ let i = 0;+ while (i < n - 2 && u > x[i + 1]) i++;+ const h = x[i + 1] - x[i];+ const s = (u - x[i]) / h;+ const s2 = s * s;+ const s3 = s2 * s;+ const v = (2 * s3 - 3 * s2 + 1) * y[i] + (s3 - 2 * s2 + s) * h * m[i] + (-2 * s3 + 3 * s2) * y[i + 1] + (s3 - s2) * h * m[i + 1];+ // Monotone by construction; held to the segment's own ends against float error.+ return Math.min(y[i + 1], Math.max(y[i], v));+ };+}++export const isIdentityKeys = (k: readonly (readonly [number, number])[]) => k.length === 2 && k[0][0] === 0 && k[0][1] === 0 && k[1][0] === 1 && k[1][1] === 1;+export const isIdentityTiming = (g: GroupTiming | undefined) => !g || (g.rate === 1 && isIdentityKeys(g.keys));++/** The suggested shapes under the graph: each writes 5 keys sampled from a named curve. */+export const SHAPES: { id: string; label: string; f: Ease }[] = [+ { id: "even", label: "Even", f: (u) => u },+ { id: "in", label: "Ease in", f: quad.in },+ { id: "out", label: "Ease out", f: quad.out },+ { id: "in-out", label: "Ease in and out", f: cubic.inOut },+ { id: "late", label: "Late start", f: (u) => (u < 0.4 ? 0 : sine.out((u - 0.4) / 0.6)) },+];++export function shapeKeys(id: string): WarpKeys {+ const s = SHAPES.find((x) => x.id === id) ?? SHAPES[0];+ if (s.id === "even") return IDENTITY_KEYS.map((k) => [...k] as [number, number]);+ return [0, 0.25, 0.5, 0.75, 1].map((u) => [u, Math.round(s.f(u) * 1e4) / 1e4] as [number, number]);+}++// ---------------------------------------------------------------------------+// Rates++/** The shortest an event may last after a rate change (seconds). */+export const MIN_EVENT = 0.2;++const groupStart = (events: readonly MotionEvent[]) => Math.min(...events.map((e) => e.start));++/** Where a group's last event ends at `rate`. */+function groupEnd(events: readonly MotionEvent[], rate: number): number {+ const g0 = groupStart(events);+ return Math.max(...events.map((e) => g0 + (e.start - g0) / rate + Math.max(MIN_EVENT, e.dur / rate)));+}++/**+ * The rates a group may take: up to 2x quicker always; as slow as keeps it inside its shot and a second before the last+ * frame (never stricter than the scene's own timing). A Camera group never goes slower than 1x, so it still comes home on+ * the last frame.+ */+export function rateLimits(g: MotionGroup, windows: readonly Window[], last: number): { min: number; max: number } {+ if (g.camera) return { min: 1, max: 2 };+ if (!g.events.length) return { min: 1, max: 1 };+ const end = windows[g.window]?.[1] ?? last;+ const limit = Math.max(Math.min(end, last - 1), groupEnd(g.events, 1));+ let lo = 0.5;+ if (groupEnd(g.events, lo) <= limit + 1e-9) return { min: 0.5, max: 2 };+ let hi = 1;+ for (let i = 0; i < 40; i++) {+ const mid = (lo + hi) / 2;+ if (groupEnd(g.events, mid) <= limit + 1e-9) hi = mid;+ else lo = mid;+ }+ return { min: Math.ceil(hi * 100) / 100, max: 2 };+}++export const clampRate = (rate: number, l: { min: number; max: number }) => Math.min(l.max, Math.max(l.min, rate));++const r6 = (v: number) => Math.round(v * 1e6) / 1e6;++/**+ * The events with each retimed group's rate and warp: starts scale about the group's first start, durations by the rate+ * (never under MIN_EVENT), and every event of the group runs on the group's warp. Events of other groups are the same+ * objects; a recipe without timing gives back the same array.+ */+export function retime(events: MotionEvent[], timing: Recipe["groups"], groups: readonly MotionGroup[], windows: readonly Window[], last: number): MotionEvent[] {+ if (!timing || !Object.keys(timing).length) return events;+ const change = new Map<MotionEvent, MotionEvent>();+ for (const g of groups) {+ const t = timing[g.id];+ if (isIdentityTiming(t) || !g.events.length) continue;+ const rate = clampRate(t!.rate, rateLimits(g, windows, last));+ const warp = isIdentityKeys(t!.keys) ? undefined : warpOf(t!.keys);+ const g0 = groupStart(g.events);+ for (const e of g.events) {+ const next: MotionEvent = rate === 1 ? { ...e } : { ...e, start: r6(g0 + (e.start - g0) / rate), dur: r6(Math.max(MIN_EVENT, e.dur / rate)) };+ if (warp) next.warp = warp;+ change.set(e, next);+ }+ }+ if (!change.size) return events;+ return events.map((e) => change.get(e) ?? e);+}++/**+ * The camera's clock: inside each shot [a, b], t' = a + (b - a) × warp(min(1, local(t, a, a + (b - a) / rate))) with the+ * shot's Camera group timing; the identity without one. The camera still comes home on the last frame.+ */+export function cameraClock(windows: readonly Window[], timing: Recipe["groups"]): ((t: number) => number) | null {+ const per = windows.map((w, i) => {+ const g = timing?.[cameraGroupId(i)];+ if (isIdentityTiming(g)) return null;+ const rate = Math.min(2, Math.max(1, g!.rate));+ return { a: w[0], b: w[1], rate, warp: warpOf(g!.keys) };+ });+ if (per.every((p) => !p)) return null;+ return (t) => {+ const i = windowAt(windows, t);+ const p = per[i];+ if (!p) return t;+ const span = p.b - p.a;+ return p.a + span * p.warp(Math.min(1, local(t, p.a, p.a + span / p.rate)));+ };+}++// ---------------------------------------------------------------------------+// Pace++/** The Easy Pace choice as a pace (above 1 is calmer: the beats spread wider). */+export const paceOf = (controls: Recipe["controls"]): number => (controls?.pace === "calm" ? 1.2 : controls?.pace === "punchy" ? 0.82 : 1);++// ---------------------------------------------------------------------------+// Tracks++/** A track's value at `t`: keys sampled at k0 + (t − k0) × rate (k0: the first key), held before and after. */+export function trackValue(track: Track, t: number): number {+ const k0 = track.keys[0].t;+ return sample(track.keys, k0 + (t - k0) * track.rate);+}++export const trackAt = (r: Pick<Recipe, "tracks">, id: TrackId, t: number): number | undefined => {+ const tr = r.tracks?.[id];+ return tr ? trackValue(tr, t) : undefined;+};++/** At most this many tracks, of at most this many keys. */+export const TRACKS_MAX = 8;+export const TRACK_KEYS_MAX = 16;++/** The key of a track at `t` (within half a frame), or -1. */+export function keyIndexAt(track: Track | undefined, t: number, fps: number): number {+ if (!track) return -1;+ return track.keys.findIndex((k) => Math.abs(k.t - t) <= 0.5 / fps + 1e-9);+}++const r4 = (v: number) => Math.round(v * 1e4) / 1e4;++/**+ * The recipe with a key at `t` set to `v` (held to the track's limits): the key there takes the value, or a new key is+ * added in time order; the first key makes the track. Null when it can't (16 keys, or 8 tracks already).+ */+export function putTrackKey(r: Recipe, id: TrackId, t: number, v: number, fps: number): Recipe | null {+ const [lo, hi] = TRACK_LIMITS[id];+ const value = r4(Math.min(hi, Math.max(lo, v)));+ const at = r4(Math.min(60, Math.max(0, t)));+ const tracks = { ...(r.tracks ?? {}) };+ const tr = tracks[id];+ if (!tr) {+ if (Object.keys(tracks).length >= TRACKS_MAX) return null;+ tracks[id] = { keys: [{ t: at, v: value }], rate: 1 };+ return { ...r, tracks };+ }+ const i = keyIndexAt(tr, at, fps);+ if (i >= 0) {+ tracks[id] = { ...tr, keys: tr.keys.map((k, j) => (j === i ? { ...k, v: value } : k)) };+ return { ...r, tracks };+ }+ if (tr.keys.length >= TRACK_KEYS_MAX) return null;+ tracks[id] = { ...tr, keys: [...tr.keys, { t: at, v: value }].sort((a, b) => a.t - b.t) };+ return { ...r, tracks };+}++/** The recipe without one of a track's keys (its last key removes the track). */+export function dropTrackKey(r: Recipe, id: TrackId, index: number): Recipe {+ const tr = r.tracks?.[id];+ if (!tr) return r;+ const keys = tr.keys.filter((_, j) => j !== index);+ const tracks = { ...r.tracks };+ if (keys.length) tracks[id] = { ...tr, keys };+ else delete tracks[id];+ const out: Recipe = { ...r, tracks };+ if (!Object.keys(tracks).length) delete out.tracks;+ return out;+}++/** A key moved to `t`, kept a frame from each neighbour and inside the film. */+export function moveTrackKey(r: Recipe, id: TrackId, index: number, t: number, fps: number): Recipe {+ const tr = r.tracks?.[id];+ if (!tr || !tr.keys[index]) return r;+ const lo = index > 0 ? tr.keys[index - 1].t + 1 / fps : 0;+ const hi = index < tr.keys.length - 1 ? tr.keys[index + 1].t - 1 / fps : Math.min(60, r.duration);+ if (hi < lo) return r;+ const at = r4(Math.min(hi, Math.max(lo, t)));+ return { ...r, tracks: { ...r.tracks, [id]: { ...tr, keys: tr.keys.map((k, j) => (j === index ? { ...k, t: at } : k)) } } };+}++export const hasCameraTracks = (r: Pick<Recipe, "tracks">) => !!r.tracks && Object.keys(r.tracks).some((k) => k.startsWith("camera."));++// ---------------------------------------------------------------------------+// The extra camera++export interface CameraOffset {+ zoom: number;+ /** Design units. */+ x: number;+ y: number;+ /** Radians. */+ roll: number;+}++/**+ * The extra camera's move at clock time `tc` (Push, Drift, Rise; every one is home on the last frame) combined with+ * the camera tracks at `t`, for a frame `w` design units wide; null when there is neither (the scene as designed).+ */+export function extraCamera(r: Pick<Recipe, "camera" | "tracks">, last: number): ((t: number, tc: number, w: number) => CameraOffset) | null {+ const move = r.camera?.move ?? "scene";+ const moving = move === "push" || move === "drift" || move === "rise";+ const tracks = hasCameraTracks(r);+ if (!moving && !tracks) return null;+ const a = r.camera?.amount ?? 1;+ const drift = curve("drift");+ return (t, tc, w) => {+ const away = moving ? 1 - drift(last > 0 ? Math.min(1, Math.max(0, tc / last)) : 1) : 0;+ const o: CameraOffset = { zoom: 1, x: 0, y: 0, roll: 0 };+ if (move === "push") o.zoom = 1 - 0.05 * a * away;+ else if (move === "drift") o.x = -0.015 * a * w * away;+ else if (move === "rise") o.y = 0.015 * a * w * away;+ if (tracks) {+ o.zoom *= trackAt(r, "camera.zoom", t) ?? 1;+ o.x += (trackAt(r, "camera.x", t) ?? 0) * w;+ o.y += (trackAt(r, "camera.y", t) ?? 0) * w;+ o.roll += ((trackAt(r, "camera.roll", t) ?? 0) * Math.PI) / 180;+ }+ return o;+ };+}++// ---------------------------------------------------------------------------+// What a wrapper needs++export interface KineticTiming {+ events: MotionEvent[];+ curves?: Partial<Record<CurveName, Ease>>;+ /** The camera's clock (null: real time). */+ clock: ((t: number) => number) | null;+}++/** The editor's timing for a scene's events: groups retimed, the feel's curves and the camera's clock. */+export function kineticTiming(r: Recipe, sceneId: string, events: MotionEvent[], cuts: readonly number[], last: number): KineticTiming {+ const curves = CURVE_SETS[r.motion?.curves ?? "smooth"];+ const out: KineticTiming = { events, clock: null };+ if (Object.keys(curves).length) out.curves = curves;+ if (!r.groups || !Object.keys(r.groups).length) return out;+ const windows = shotWindows({ cuts, rest: last });+ const defs = groupDefsFor(sceneId);+ // A group retimed inside a nested scene is already timed in its copies here.+ const groups = groupsOf(defs, events, windows).filter((g) => !defs.find((d) => d.id === g.id)?.inner);+ out.events = retime(events, r.groups, groups, windows, last);+ out.clock = cameraClock(windows, r.groups);+ return out;+}++// ---------------------------------------------------------------------------+// Presets++export type PresetCategory = "motion" | "appearance" | "camera";++/** A category's fields and their values when absent. */+const FIELDS = {+ motion: { "motion.curves": "smooth", "motion.pace": undefined },+ appearance: { "finish.contrast": 0, "finish.saturation": 0, "finish.grain": 0, "finish.grainSize": 1.2 },+ camera: { "camera.move": "scene", "camera.amount": 1, "camera.breath": 1 },+} as const satisfies Record<PresetCategory, Record<string, string | number | undefined>>;++type Value = string | number | undefined;++export interface Preset {+ id: string;+ name: string;+ /** One line under its name. */+ purpose: string;+ /** Every field of its category (at most 15), by path. */+ values: Record<string, Value>;+}++export const PRESETS: Record<PresetCategory, Preset[]> = {+ motion: [+ { id: "smooth", name: "Smooth", purpose: "Calm, polished arrivals", values: { "motion.curves": "smooth", "motion.pace": undefined } },+ { id: "snappy", name: "Snappy", purpose: "Quick, decisive moves", values: { "motion.curves": "snappy", "motion.pace": 0.85 } },+ { id: "springy", name: "Springy", purpose: "Playful overshoot", values: { "motion.curves": "springy", "motion.pace": 1 } },+ { id: "steady", name: "Steady", purpose: "Even, unhurried moves", values: { "motion.curves": "steady", "motion.pace": 1.15 } },+ ],+ appearance: [+ { id: "clean", name: "Clean", purpose: "Exactly your colours", values: { "finish.contrast": 0, "finish.saturation": 0, "finish.grain": 0, "finish.grainSize": 1.2 } },+ { id: "film", name: "Film", purpose: "Fine grain and a touch of contrast", values: { "finish.contrast": 0.08, "finish.saturation": -0.05, "finish.grain": 0.025, "finish.grainSize": 1.3 } },+ { id: "rich", name: "Rich", purpose: "Deeper contrast and colour", values: { "finish.contrast": 0.15, "finish.saturation": 0.15, "finish.grain": 0, "finish.grainSize": 1.2 } },+ { id: "soft", name: "Soft", purpose: "Lifted and gentle", values: { "finish.contrast": -0.1, "finish.saturation": -0.1, "finish.grain": 0.015, "finish.grainSize": 1.6 } },+ ],+ camera: [+ { id: "scene", name: "Scene's own", purpose: "The scene's authored camera", values: { "camera.move": "scene", "camera.amount": 1, "camera.breath": 1 } },+ { id: "locked", name: "Locked off", purpose: "No camera move", values: { "camera.move": "locked", "camera.amount": 1, "camera.breath": 0 } },+ { id: "push", name: "Slow push", purpose: "A gentle push in", values: { "camera.move": "push", "camera.amount": 1, "camera.breath": 1 } },+ { id: "drift", name: "Drift", purpose: "A slow sideways float", values: { "camera.move": "drift", "camera.amount": 1, "camera.breath": 1 } },+ ],+};++/** A value at a path ("finish.grain") in a recipe, or its default when absent. */+export function valueAt(r: Recipe, category: PresetCategory, path: string): Value {+ const [obj, key] = path.split(".") as [keyof Recipe, string];+ const v = (r[obj] as Record<string, Value> | undefined)?.[key];+ return v === undefined ? (FIELDS[category] as Record<string, Value>)[path] : v;+}++/** The preset whose values the recipe has exactly, or "custom". */+export function presetOf(category: PresetCategory, r: Recipe): string {+ const hit = PRESETS[category].find((p) => Object.entries(p.values).every(([path, v]) => valueAt(r, category, path) === v));+ return hit?.id ?? "custom";+}++/** Sets one value (undefined: removes it), dropping defaults and empty objects. */+export function setValue(r: Recipe, path: string, v: Value | boolean): Recipe {+ const [obj, key] = path.split(".") as ["motion" | "finish" | "camera" | "look", string];+ const next = { ...((r[obj] as Record<string, unknown> | undefined) ?? {}) };+ if (v === undefined) delete next[key];+ else next[key] = v;+ return tidyRecipe({ ...r, [obj]: next } as Recipe);+}++/** The recipe with a preset's values. */+export function applyPreset(category: PresetCategory, id: string, r: Recipe): Recipe {+ const p = PRESETS[category].find((x) => x.id === id);+ if (!p) return r;+ let out = r;+ for (const [path, v] of Object.entries(p.values)) out = setValue(out, path, v);+ return out;+}++/** The recipe without the editor's default values (so an untouched scene's recipe is exactly the designed one). */+export function tidyRecipe(r: Recipe): Recipe {+ const out: Recipe = { ...r };+ const drop = <K extends "motion" | "finish" | "camera" | "look">(k: K, defaults: Record<string, unknown>) => {+ const o = out[k] as Record<string, unknown> | undefined;+ if (!o) return;+ const kept = Object.fromEntries(Object.entries(o).filter(([key, v]) => v !== undefined && v !== defaults[key]));+ if (Object.keys(kept).length) (out as Record<string, unknown>)[k] = kept;+ else delete out[k];+ };+ drop("motion", { curves: "smooth" });+ drop("finish", { contrast: 0, saturation: 0, grain: 0, grainSize: 1.2 });+ drop("camera", { move: "scene", amount: 1, breath: 1 });+ drop("look", { light: true });+ if (out.groups) {+ const kept = Object.entries(out.groups).filter(([, g]) => !isIdentityTiming(g));+ if (kept.length) out.groups = Object.fromEntries(kept);+ else delete out.groups;+ }+ if (out.tracks && !Object.keys(out.tracks).length) delete out.tracks;+ return out;+}diff --git a/src/lib/motion/finish.ts b/src/lib/motion/finish.tsnew file mode 100644index 00000000..8b86f49e--- /dev/null+++ b/src/lib/motion/finish.ts@@ -0,0 +1,112 @@+/**+ * The finish over a finished frame (pure): contrast, saturation and seeded film grain. The scene wrappers work out the+ * values at each time (tracks included) and put them on the display list; the drawer applies them once per output+ * frame, after motion blur. Contrast and saturation follow the CSS filter formulas exactly, so the canvas filter and the+ * pixel pass (for a browser without canvas filters) give the same picture. The same seed and frame always get the same+ * grain; neighbouring frames differ.+ */++import { rng } from "./random";+import type { Recipe } from "./recipe";+import { trackAt } from "./edit";++export interface Finish {+ /** -0.5 to 0.5 (0: as drawn). */+ contrast: number;+ /** -1 to 1 (0: as drawn; -1: grey). */+ saturation: number;+ /** 0 to 0.1. */+ grain: number;+ /** 1 to 3: a grain dot's size in pixels at 1080 on the short side. */+ grainSize: number;+ seed: number;+ /** The output frame's index (the grain's offset). */+ frame: number;+}++export const GRAIN_SIZE = 1.2;+/** The grain's strength in the overlay for a grain amount (a 2.5 % grain lays the noise at 7.5 %). */+export const GRAIN_GAIN = 3;+/** The noise tile's side. */+export const GRAIN_TILE = 256;++export const neutralFinish = (f: Pick<Finish, "contrast" | "saturation" | "grain">) => f.contrast === 0 && f.saturation === 0 && f.grain <= 0;++/** The finish at `t` (its tracks replace the slider values), or null when it changes nothing. */+export function finishAt(r: Recipe, t: number): Finish | null {+ if (!r.finish && !r.tracks) return null;+ const contrast = trackAt(r, "finish.contrast", t) ?? r.finish?.contrast ?? 0;+ const saturation = trackAt(r, "finish.saturation", t) ?? r.finish?.saturation ?? 0;+ const grain = trackAt(r, "finish.grain", t) ?? r.finish?.grain ?? 0;+ if (neutralFinish({ contrast, saturation, grain })) return null;+ return { contrast, saturation, grain, grainSize: r.finish?.grainSize ?? GRAIN_SIZE, seed: r.seed, frame: Math.floor(t * r.fps + 1e-6) };+}++/** The CSS filter for the grade ("none" when neutral). */+export function cssFilter(f: Pick<Finish, "contrast" | "saturation">): string {+ const parts: string[] = [];+ if (f.contrast !== 0) parts.push(`contrast(${(1 + f.contrast).toFixed(4)})`);+ if (f.saturation !== 0) parts.push(`saturate(${(1 + f.saturation).toFixed(4)})`);+ return parts.length ? parts.join(" ") : "none";+}++const c01 = (v: number) => (v < 0 ? 0 : v > 1 ? 1 : v);++/**+ * The grade as a pixel pass over RGBA bytes, in place: contrast(c) then saturate(s) with the Filter Effects formulas+ * (each step clamped, as a browser's filter primitives are).+ */+export function gradePixels(data: Uint8ClampedArray, f: Pick<Finish, "contrast" | "saturation">): void {+ const c = Number((1 + f.contrast).toFixed(4));+ const s = Number((1 + f.saturation).toFixed(4));+ const doC = f.contrast !== 0;+ const doS = f.saturation !== 0;+ if (!doC && !doS) return;+ const m = [0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s, 0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s, 0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s];+ for (let i = 0; i < data.length; i += 4) {+ let r = data[i] / 255;+ let g = data[i + 1] / 255;+ let b = data[i + 2] / 255;+ if (doC) {+ r = c01((r - 0.5) * c + 0.5);+ g = c01((g - 0.5) * c + 0.5);+ b = c01((b - 0.5) * c + 0.5);+ }+ if (doS) {+ const R = c01(m[0] * r + m[1] * g + m[2] * b);+ const G = c01(m[3] * r + m[4] * g + m[5] * b);+ const B = c01(m[6] * r + m[7] * g + m[8] * b);+ r = R;+ g = G;+ b = B;+ }+ data[i] = Math.round(r * 255);+ data[i + 1] = Math.round(g * 255);+ data[i + 2] = Math.round(b * 255);+ }+}++const tiles = new Map<number, Uint8ClampedArray>();++/** The grain's noise tile for a seed: GRAIN_TILE² grey levels, made once. */+export function grainTile(seed: number): Uint8ClampedArray {+ let t = tiles.get(seed);+ if (!t) {+ t = new Uint8ClampedArray(GRAIN_TILE * GRAIN_TILE);+ for (let i = 0; i < t.length; i++) t[i] = Math.floor(rng(seed, "grain", i) * 256);+ if (tiles.size > 8) tiles.clear();+ tiles.set(seed, t);+ }+ return t;+}++/** Where frame `frame`'s grain starts in the tile (whole tile pixels). */+export function grainOffset(seed: number, frame: number): [number, number] {+ return [Math.floor(rng(seed, "grain-offset", frame, 0) * GRAIN_TILE), Math.floor(rng(seed, "grain-offset", frame, 1) * GRAIN_TILE)];+}++/** A grain dot's size in pixels on a canvas whose short side is `short` pixels. */+export const grainScale = (f: Pick<Finish, "grainSize">, short: number) => Math.max(0.25, f.grainSize * (short / 1080));++/** The export bitrate's quality factor (High: × 1.6). */+export const qualityFactor = (q: Recipe["export"]["quality"]) => (q === "high" ? 1.6 : 1);diff --git a/src/lib/motion/kinetic-catalog.ts b/src/lib/motion/kinetic-catalog.tsnew file mode 100644index 00000000..52f07c1b--- /dev/null+++ b/src/lib/motion/kinetic-catalog.ts@@ -0,0 +1,156 @@+/**+ * Kinetic's scene catalogue (pure, bundled with the page: no data route). Built from Marketing's code-drawn templates,+ * so names, fields, Easy choices, sizes and lengths stay in one place; this file adds each scene's address, what the+ * editor offers on it (a clip under the words, the Pro controls), its motion groups and the four examples.+ */++import { TEMPLATES, type MarketingTemplate } from "@/lib/catalog/marketing";+import { applyPreset, type PresetCategory } from "./edit";+import { CLIP_SCENES, groupDefsFor, groupIdsFor, type MotionGroupDef } from "./kinetic-groups";+import { normalizeRecipe, type Recipe } from "./recipe";+import { END_CARD_VARIANTS, type EndCardVariant } from "./scenes/end-card/shared";+import type { ScenePlan } from "./scene";+import { SHOWCASES, showcaseRecipe } from "./showcase";+import { initialState, templateLengths, templateRecipe, templateSizes, type TemplateBrand } from "./template";++export type KineticSlug = "kinetic-headline" | "line-reveal" | "logo-sting" | "feature-cards" | "stat-dashboard" | "starburst" | "offer-badge" | "big-number" | "quote" | "end-card";++export interface KineticEntry {+ slug: KineticSlug;+ /** The Marketing template it comes from (fields, Easy choices, sizes, lengths, showcase). */+ template: string;+ name: string;+ /** One line of purpose. */+ blurb: string;+ /** The scene ids it plays: one, or the end card's five styles. */+ scenes: string[];+ /** It takes the person's own clip under its words. */+ clip: boolean;+ /** Which wrapper-level Pro controls apply (end cards have no Pace, Look or Ground light). */+ pro: { pace: boolean; look: boolean; light: boolean };+ groups: MotionGroupDef[];+}++const ORDER: { slug: KineticSlug; template: string; blurb: string }[] = [+ { slug: "kinetic-headline", template: "ms-kinetic-headline", blurb: "Your promise sets itself word by word, then resolves to your logo." },+ { slug: "big-number", template: "ms-big-number", blurb: "One huge stat counts up to its value, with a caption and your logo." },+ { slug: "end-card", template: "ms-end-card", blurb: "Your logo, line and call to action in one of five animated styles." },+ { slug: "quote", template: "ms-five-star-quote", blurb: "Five stars fill, then a customer's words set line by line." },+ { slug: "logo-sting", template: "ms-logo-sting", blurb: "Shapes converge and click together into your mark." },+ { slug: "feature-cards", template: "ms-feature-cards", blurb: "Rounded cards fly in and stack, one benefit each." },+ { slug: "stat-dashboard", template: "ms-dashboard-zoom", blurb: "The camera pushes into a dashboard as a key number counts up." },+ { slug: "line-reveal", template: "m2-line-reveal", blurb: "One line draws your product, then the real product fills in." },+ { slug: "starburst", template: "m2-retro-starburst", blurb: "A retro starburst turns behind your product and headline." },+ { slug: "offer-badge", template: "m2-offer-badge", blurb: "An offer badge pops and turns as your product slides in." },+];++const byTemplate = new Map(TEMPLATES.map((t) => [t.id, t]));++export const templateOf = (e: Pick<KineticEntry, "template">): MarketingTemplate => byTemplate.get(e.template)!;++export const KINETIC_SCENES: KineticEntry[] = ORDER.map((o) => {+ const t = byTemplate.get(o.template)!;+ const endCard = t.scene!.startsWith("end-card/");+ const scenes = endCard ? END_CARD_VARIANTS.map((v) => `end-card/${v}`) : [t.scene!];+ return {+ slug: o.slug,+ template: o.template,+ name: t.name,+ blurb: o.blurb,+ scenes,+ clip: scenes.every((s) => CLIP_SCENES.includes(s)),+ pro: { pace: !endCard, look: !endCard, light: !endCard },+ groups: groupDefsFor(scenes[0]),+ };+});++export const KINETIC_SLUGS = KINETIC_SCENES.map((e) => e.slug);++export const entryBySlug = (slug: string | null | undefined): KineticEntry | undefined => KINETIC_SCENES.find((e) => e.slug === slug);++/** The entry a recipe belongs to: by its template first, then by its scene (Click to Ad's end cards have no template). */+export function entryForRecipe(r: Pick<Recipe, "scene" | "controls">): KineticEntry | undefined {+ const t = r.controls?.template;+ return (typeof t === "string" && KINETIC_SCENES.find((e) => e.template === t)) || KINETIC_SCENES.find((e) => e.scenes.includes(r.scene));+}++export interface KineticExample {+ slug: KineticSlug;+ /** The end card's style. */+ style?: EndCardVariant;+ label: string;+ /** One line of what it shows. */+ purpose: string;+ /** The presets it is finished with (Appearance, Motion, Camera), so it is more than the scene's own tile. */+ presets: Partial<Record<PresetCategory, string>>;+}++/** The four examples on the opening screen: each scene finished with a look, a feel and a camera. */+export const KINETIC_EXAMPLES: KineticExample[] = [+ { slug: "kinetic-headline", label: "Kinetic Headline", purpose: "A launch line in film grain, with a slow push", presets: { appearance: "film", camera: "push" } },+ { slug: "big-number", label: "Big Number", purpose: "A record stat that lands hard, in rich colour", presets: { appearance: "rich", motion: "snappy" } },+ { slug: "end-card", style: "glint", label: "Logo End Card", purpose: "Your logo caught by a sweep of light", presets: { appearance: "film" } },+ { slug: "quote", label: "Five-Star Quote", purpose: "A review set softly, word by word", presets: { appearance: "soft", motion: "steady" } },+];++/** An example's opening recipe: its scene's showcase with the example's presets, in the feed's 4:5 where it is offered. */+export function exampleRecipe(x: KineticExample): Recipe {+ const e = entryBySlug(x.slug)!;+ let r = startRecipe(e, { style: x.style });+ if (templateSizes(templateOf(e)).includes("4:5")) r = { ...r, size: "4:5" };+ for (const [category, id] of Object.entries(x.presets) as [PresetCategory, string][]) r = applyPreset(category, id, r);+ return r;+}++/**+ * Where a scene rests when it can't play (reduced motion) or is shown still: its showcase's telling moment when that+ * comes before the end (Kinetic Headline: the headline set, before its end card), else its last frame.+ */+export function restingTime(plan: ScenePlan, r: Pick<Recipe, "controls">): number {+ const id = r.controls?.template;+ const poster = typeof id === "string" ? SHOWCASES[id]?.poster : undefined;+ const at = poster ? plan.timeline.events.find((e) => e.id === poster)?.start : undefined;+ return typeof at === "number" ? Math.min(plan.rest, Math.max(0, Math.round((at - 0.08) * 100) / 100)) : plan.rest;+}++/** The scenes that take a clip, for the opening screen's chip. */+export const clipScenes = () => KINETIC_SCENES.filter((e) => e.clip).map((e) => e.slug);++/** Every group id a scene can hold in a recipe (its groups and a Camera group per shot). */+export const groupIdsOf = (e: KineticEntry): string[] => groupIdsFor(e.scenes[0]);++/** A saved or typed recipe, checked and held to its scene (a clip it can't take and unknown groups are dropped). */+export function normalizeKinetic(input: unknown): { recipe: Recipe; entry: KineticEntry } | null {+ let r: Recipe;+ try {+ r = normalizeRecipe(input);+ } catch {+ return null;+ }+ const entry = entryForRecipe(r);+ if (!entry || !entry.scenes.includes(r.scene)) return null;+ const t = templateOf(entry);+ // Click to Ad's end cards keep their own length (2 to 3 s), which the end card's own limits hold too.+ const recipe = normalizeRecipe(r, templateLengths(t), { clip: entry.clip, groups: groupIdsOf(entry) });+ return { recipe, entry };+}++/** A scene's opening recipe: its showcase (the person's stored brand when they set one), the end card in `style`. */+export function startRecipe(e: KineticEntry, o: { brand?: TemplateBrand | null; style?: EndCardVariant | null } = {}): Recipe {+ const t = templateOf(e);+ if (!o.brand) {+ const show = showcaseRecipe(t.id, t.scene!, templateLengths(t).default);+ if (show) {+ const style = o.style && e.slug === "end-card" ? o.style : null;+ return style ? { ...show, scene: `end-card/${style}`, controls: { ...show.controls, style } } : show;+ }+ }+ const state = initialState(t, o.brand ?? null);+ if (o.style && e.slug === "end-card") state.controls.style = o.style;+ return templateRecipe(t, state);+}++/** The scene's address for a recipe ("/kinetic?scene=end-card&style=glint"). */+export function kineticHref(e: Pick<KineticEntry, "slug">, style?: string | null): string {+ return `/kinetic?scene=${e.slug}${style ? `&style=${style}` : ""}`;+}diff --git a/src/lib/motion/kinetic-doc.ts b/src/lib/motion/kinetic-doc.tsnew file mode 100644index 00000000..f61aece0--- /dev/null+++ b/src/lib/motion/kinetic-doc.ts@@ -0,0 +1,152 @@+/**+ * What Kinetic's editor edits (pure): a recipe, plus the brand's logo while the end card's "Name" choice hides it. Every+ * change here makes a new document, so the editor's history keeps each one as it was.+ */++import { entryForRecipe, startRecipe, templateOf, type KineticEntry } from "./kinetic-catalog";+import { tidyRecipe } from "./edit";+import type { Recipe, VideoLayer } from "./recipe";+import type { SizeSpec } from "./sizes";+import type { TemplateBrand } from "./template";++export interface KineticDoc {+ recipe: Recipe;+ /** The brand's logo, kept while the end card's "Name" choice sets the name in type instead. */+ logo: string | null;+}++const HEX = /^#[0-9a-f]{6}$/i;++export function docFrom(recipe: Recipe): KineticDoc {+ return { recipe, logo: recipe.brand.logo ?? null };+}++const isEndCard = (r: Recipe) => r.scene.startsWith("end-card/");++/** A typed field, exactly as typed (an empty one is left out, as Marketing does). */+export function setField(d: KineticDoc, e: KineticEntry, key: string, value: string): KineticDoc {+ const f = templateOf(e).fields?.find((x) => x.key === key);+ const v = f ? value.slice(0, f.max) : value;+ const fields = { ...d.recipe.fields };+ if (v.trim()) fields[key] = v;+ else delete fields[key];+ return { ...d, recipe: { ...d.recipe, fields } };+}++/** The Easy choice in a group: a style picks the end card's scene; Name hides the logo; Pace clears Pro's pace. */+export function setEasy(d: KineticDoc, e: KineticEntry, group: string, choice: string): KineticDoc {+ const g = templateOf(e).easy?.find((x) => x.id === group);+ if (!g || !g.choices.some((c) => c.id === choice)) return d;+ const r = d.recipe;+ const controls = { ...(r.controls ?? {}), [group]: choice };+ if (g.scene) return { ...d, recipe: { ...r, scene: `${g.scene}/${choice}`, controls } };+ let next: Recipe = { ...r, controls };+ if (group === "mark" && isEndCard(r)) {+ const brand = { ...r.brand };+ if (choice === "name") delete brand.logo;+ else if (d.logo) brand.logo = d.logo;+ next = { ...next, brand };+ }+ if (group === "pace" && next.motion?.pace !== undefined) {+ const motion = { ...next.motion };+ delete motion.pace;+ next = tidyRecipe({ ...next, motion });+ }+ return { ...d, recipe: next };+}++/** The Easy choice a group shows (none when Pro moved the value it sets: Pace under a Pro pace). */+export function easyValue(d: KineticDoc, e: KineticEntry, group: string): string | null {+ if (group === "pace" && d.recipe.motion?.pace !== undefined) return null;+ const g = templateOf(e).easy?.find((x) => x.id === group);+ if (!g) return null;+ if (g.scene) return d.recipe.scene.split("/")[1] ?? g.choices[0].id;+ if (group === "mark" && isEndCard(d.recipe)) return d.recipe.brand.logo ? "logo" : d.logo ? "name" : String(d.recipe.controls?.mark ?? "logo");+ const v = d.recipe.controls?.[group];+ return typeof v === "string" ? v : g.choices[0].id;+}++export function brandOf(d: KineticDoc): TemplateBrand {+ const b = d.recipe.brand;+ return { name: b.name, colors: [...b.colors], fonts: { heading: b.fonts.heading ?? "Inter", body: b.fonts.body ?? "Inter" }, logo: d.logo };+}++export function setBrand(d: KineticDoc, b: TemplateBrand): KineticDoc {+ const r = d.recipe;+ const hideLogo = isEndCard(r) && r.controls?.mark === "name";+ const brand: Recipe["brand"] = { name: b.name.slice(0, 120), colors: b.colors.filter((c) => HEX.test(c)).slice(0, 8), fonts: { heading: b.fonts.heading, body: b.fonts.body }, ...(b.logo && !hideLogo && { logo: b.logo }) };+ const fields = isEndCard(r) ? { ...r.fields, brand: brand.name } : r.fields;+ return { recipe: { ...r, brand, fields }, logo: b.logo ?? null };+}++export function setProduct(d: KineticDoc, url: string | null): KineticDoc {+ const media = { ...(d.recipe.media ?? {}) };+ if (url) media.product = url;+ else delete media.product;+ const recipe: Recipe = { ...d.recipe, media };+ if (!Object.keys(media).length) delete recipe.media;+ return { ...d, recipe };+}++export const setSize = (d: KineticDoc, size: SizeSpec): KineticDoc => ({ ...d, recipe: { ...d.recipe, size } });++export const setDuration = (d: KineticDoc, duration: number): KineticDoc => ({ ...d, recipe: { ...d.recipe, duration } });++export const setFps = (d: KineticDoc, fps: Recipe["fps"]): KineticDoc => ({ ...d, recipe: { ...d.recipe, fps } });++export const setExport = (d: KineticDoc, x: Partial<Recipe["export"]>): KineticDoc => ({ ...d, recipe: { ...d.recipe, export: { ...d.recipe.export, ...x } } });++/** A Pro change (presets, sliders, groups, tracks), tidied so a value back at its default leaves the recipe as designed. */+export const setPro = (d: KineticDoc, f: (r: Recipe) => Recipe): KineticDoc => ({ ...d, recipe: tidyRecipe(f(d.recipe)) });++export const hasTiming = (r: Recipe): boolean => !!(r.groups && Object.keys(r.groups).length) || !!(r.tracks && Object.keys(r.tracks).length);++/** Every group and track edit cleared (one undo step). */+export function clearTiming(d: KineticDoc): KineticDoc {+ const recipe = { ...d.recipe };+ delete recipe.groups;+ delete recipe.tracks;+ return { ...d, recipe };+}++export function setClip(d: KineticDoc, layer: VideoLayer | null): KineticDoc {+ const recipe = { ...d.recipe };+ if (layer) recipe.layers = { ...(recipe.layers ?? {}), video: layer };+ else {+ delete recipe.layers;+ if (recipe.tracks?.["clip.dim"]) {+ const tracks = { ...recipe.tracks };+ delete tracks["clip.dim"];+ if (Object.keys(tracks).length) recipe.tracks = tracks;+ else delete recipe.tracks;+ }+ }+ return { ...d, recipe };+}++/** A new clip under the words: a light dim and a full scrim in the ground colour, so every look keeps its words readable. */+export const DEFAULT_CLIP: Omit<VideoLayer, "src"> = { from: 0, fit: "cover", dim: 0.15, scrim: "full" };++/**+ * Another scene, keeping what carries over: the brand (and its logo), the size when the scene comes in it, and the+ * export settings. Its own words, choices and timing start from its showcase.+ */+export function switchScene(d: KineticDoc, to: KineticEntry, brand: TemplateBrand | null): KineticDoc {+ const r = startRecipe(to, { brand });+ const from = entryForRecipe(d.recipe);+ const keepSize = typeof d.recipe.size === "string" && from?.slug !== to.slug;+ return docFrom({ ...r, ...(keepSize && { size: d.recipe.size }), fps: d.recipe.fps, export: d.recipe.export });+}++/** The words a saved result is listed by: the scene's name and the first typed words. */+export function docWords(d: KineticDoc, e: KineticEntry): { first: string; prompt: string } {+ const t = templateOf(e);+ const typed = (t.fields ?? []).map((f) => (d.recipe.fields[f.key] ?? "").replace(/\*/g, "").trim()).filter(Boolean);+ const first = (typed[0] ?? d.recipe.brand.name).split(/\s+/).slice(0, 5).join(" ");+ return { first, prompt: [d.recipe.brand.name, ...typed].filter(Boolean).join(" · ").slice(0, 2000) };+}++/** The person's own stored files a recipe names (logo, picture, clip). */+export function docFiles(r: Recipe): string[] {+ return [r.brand.logo, r.media?.product].filter((u): u is string => !!u?.startsWith("/api/files/"));+}diff --git a/src/lib/motion/kinetic-groups.ts b/src/lib/motion/kinetic-groups.tsnew file mode 100644index 00000000..d9edf068--- /dev/null+++ b/src/lib/motion/kinetic-groups.ts@@ -0,0 +1,122 @@+/**+ * Every scene's motion groups (pure): the named parts a person retimes in Kinetic's editor ("Number", "Caption",+ * "Logo"…), each a list of event id prefixes or event group names it takes. Every event of every scene belongs to+ * exactly one group (tests/kinetic-catalog.test.ts checks it at every size and length, with and without a logo and a+ * picture), so no visitor ever sees an internal id. Events of kind "camera" belong to their shot's Camera group.+ *+ * Kept apart from kinetic-catalog.ts so the scene wrappers read it without loading the Marketing catalogue.+ */++import type { MotionEvent } from "./tween";++export interface MotionGroupDef {+ id: string;+ /** What a visitor reads. */+ label: string;+ /** Event id prefixes ("cta" takes "cta" and "cta.pill") or event group names. */+ match: string[];+ /**+ * Retimed inside a scene drawn within this one (the Kinetic Headline's end card): its events here are copies that+ * already carry the timing, so the outer timeline doesn't retime them again.+ */+ inner?: true;+}++const END_CARD_GROUPS: MotionGroupDef[] = [+ { id: "ground", label: "Background", match: ["panel", "panels", "iris", "bloom"] },+ { id: "logo", label: "Logo", match: ["logo", "mark", "brand", "glint"] },+ { id: "headline", label: "Line", match: ["headline"] },+ { id: "cta", label: "Call to action", match: ["cta"] },+ { id: "site", label: "Web address", match: ["site"] },+];++/** By scene id ("end-card/…" scenes share one list). */+const GROUPS: Record<string, MotionGroupDef[]> = {+ "end-card": END_CARD_GROUPS,+ "marketing/kinetic-headline": [+ { id: "words", label: "Words", match: ["word", "mark", "words"] },+ { id: "wipe", label: "Wipe", match: ["panel"] },+ // The same ids as the end card's own groups: the card inside the headline is retimed by them too.+ { id: "logo", label: "Logo", match: ["card.logo", "card.brand", "card.mark"], inner: true },+ { id: "cta", label: "Call to action", match: ["card.cta"], inner: true },+ { id: "site", label: "Web address", match: ["card.site"], inner: true },+ ],+ "marketing/line-reveal": [+ { id: "outline", label: "Line drawing", match: ["trace", "arch"] },+ { id: "picture", label: "Picture", match: ["ground", "fill", "shadow"] },+ { id: "headline", label: "Headline", match: ["head"] },+ { id: "cta", label: "Call to action", match: ["cta"] },+ { id: "brand", label: "Logo", match: ["brand"] },+ ],+ "marketing/starburst": [+ { id: "burst", label: "Starburst", match: ["rays", "halo"] },+ { id: "picture", label: "Picture", match: ["drop", "spin", "shadow"] },+ { id: "badge", label: "Badge", match: ["badge"] },+ { id: "headline", label: "Headline", match: ["band", "head"] },+ ],+ "marketing/offer-badge": [+ { id: "badge", label: "Badge", match: ["badge"] },+ { id: "picture", label: "Picture", match: ["slide", "shadow"] },+ { id: "headline", label: "Headline", match: ["head"] },+ { id: "cta", label: "Call to action", match: ["cta"] },+ ],+ "marketing/feature-cards": [+ { id: "headline", label: "Headline", match: ["head"] },+ { id: "cards", label: "Cards", match: ["card", "check"] },+ { id: "brand", label: "Logo", match: ["brand"] },+ ],+ "marketing/stat-dashboard": [+ { id: "panel", label: "Dashboard", match: ["panel", "grid"] },+ { id: "chart", label: "Chart", match: ["bar", "bars", "line", "area", "dot"] },+ { id: "number", label: "Number", match: ["count"] },+ { id: "label", label: "Label", match: ["label"] },+ { id: "brand", label: "Logo", match: ["brand"] },+ ],+ "marketing/logo-sting": [+ { id: "lines", label: "Lines", match: ["lines"] },+ { id: "shapes", label: "Shapes", match: ["shard"] },+ { id: "logo", label: "Logo", match: ["flash", "ring", "settle", "glint"] },+ { id: "tagline", label: "Tagline", match: ["tagline"] },+ ],+ "marketing/big-number": [+ { id: "number", label: "Number", match: ["count", "stat"] },+ { id: "caption", label: "Caption", match: ["cap", "caption"] },+ { id: "mark", label: "Logo", match: ["mark"] },+ ],+ "marketing/quote": [+ { id: "stars", label: "Stars", match: ["outline", "star", "stars"] },+ { id: "quote", label: "Quote", match: ["line", "quote"] },+ { id: "name", label: "Name", match: ["rule", "name"] },+ { id: "brand", label: "Logo", match: ["brand"] },+ ],+};++/** The scenes that take the person's own clip under their words. */+export const CLIP_SCENES: readonly string[] = ["marketing/kinetic-headline", "marketing/big-number", "marketing/quote", "marketing/logo-sting", "marketing/feature-cards"];++/** How many shots (windows between cuts) a scene has. */+const WINDOWS: Record<string, number> = { "marketing/kinetic-headline": 2 };++/** A scene's motion groups (the end card's five styles share one list). */+export function groupDefsFor(sceneId: string): MotionGroupDef[] {+ return GROUPS[sceneId] ?? (sceneId.startsWith("end-card/") ? GROUPS["end-card"] : []);+}++export const windowCountFor = (sceneId: string): number => WINDOWS[sceneId] ?? 1;++/** The Camera group's id in shot `w` (0-based): "camera", then "camera-2"… */+export const cameraGroupId = (w: number): string => (w === 0 ? "camera" : `camera-${w + 1}`);++/** Every group id a scene can have (its own and one Camera group per shot). */+export function groupIdsFor(sceneId: string): string[] {+ const n = windowCountFor(sceneId);+ return [...groupDefsFor(sceneId).map((g) => g.id), ...Array.from({ length: n }, (_, i) => cameraGroupId(i))];+}++const takes = (m: string, e: MotionEvent) => e.id === m || e.id.startsWith(`${m}.`) || e.group === m;++/** The ids of every group that takes an event (exactly one for a well-formed scene; "camera" for a camera event). */+export function groupMatches(defs: readonly MotionGroupDef[], e: MotionEvent): string[] {+ if (e.kind === "camera") return ["camera"];+ return defs.filter((g) => g.match.some((m) => takes(m, e))).map((g) => g.id);+}diff --git a/src/lib/motion/recipe.ts b/src/lib/motion/recipe.tsindex 48efe174..0e631a3d 100644--- a/src/lib/motion/recipe.ts+++ b/src/lib/motion/recipe.ts@@ -2,10 +2,16 @@* A recipe: everything a Kinetic Motion clip is made from, as JSON (pure). The scene, the seed, the size and rate, the* typed words, the brand, the person's own files, the scene's control values and the export settings. It is saved* with the result (params.extra.motion), so the same clip can be made again.+ *+ * Kinetic's editor adds optional fields (motion feel and pace, a finish, an extra camera, the ground light, retimed+ * motion groups, parameter tracks and a clip under the words). A recipe without them is the scene exactly as designed,+ * and `v` stays 1.*/import { z } from "zod";+import { CURVES, type CurveName } from "./ease";import { rng } from "./random";+import { customSizeProblem } from "./sizes";/** A recipe is at most this big as JSON. */export const RECIPE_MAX_BYTES = 64 * 1024;@@ -17,12 +23,78 @@ const File = z.max(500).refine((u) => (u.startsWith("/api/files/") || u.startsWith("/previews/")) && !u.includes(".."), "A stored file or a sample picture");+/** A clip the words go over: only the person's own stored file. */+const Clip = z+ .string()+ .max(500)+ .refine((u) => u.startsWith("/api/files/") && !u.includes(".."), "A stored file");++/** The motion feels a recipe can take (ease.ts CURVE_SETS). */+export const CURVE_SET_IDS = ["smooth", "snappy", "springy", "steady"] as const;+export type CurveSetId = (typeof CURVE_SET_IDS)[number];++/** The extra camera moves (every one comes home on the last frame). */+export const CAMERA_MOVES = ["scene", "locked", "push", "drift", "rise"] as const;+export type CameraMoveId = (typeof CAMERA_MOVES)[number];++/** The numbers a parameter track can animate, with their limits (camera x and y: a share of the frame's width; roll: degrees). */+export const TRACK_LIMITS = {+ "camera.zoom": [0.8, 1.25],+ "camera.x": [-0.1, 0.1],+ "camera.y": [-0.1, 0.1],+ "camera.roll": [-10, 10],+ "finish.contrast": [-0.5, 0.5],+ "finish.saturation": [-1, 1],+ "finish.grain": [0, 0.1],+ "clip.dim": [0, 0.8],+} as const satisfies Record<string, readonly [number, number]>;+export type TrackId = keyof typeof TRACK_LIMITS;+export const TRACK_IDS = Object.keys(TRACK_LIMITS) as TrackId[];++const CURVE_NAMES = Object.keys(CURVES) as [CurveName, ...CurveName[]];++/** Whether warp keys run from [0, 0] to [1, 1] with u rising and p never falling. */+export function validWarpKeys(k: readonly (readonly [number, number])[]): boolean {+ if (k.length < 2) return false;+ const a = k[0];+ const b = k[k.length - 1];+ return a[0] === 0 && a[1] === 0 && b[0] === 1 && b[1] === 1 && k.every((x, i) => i === 0 || (x[0] > k[i - 1][0] && x[1] >= k[i - 1][1]));+}++/** A motion group's timing: its warp keys [u, p] and its rate. */+export const GroupTimingSchema = z.object({+ keys: z+ .array(z.tuple([z.number().min(0).max(1), z.number().min(0).max(1)]))+ .min(2)+ .max(8)+ .refine(validWarpKeys, "Keys from [0, 0] to [1, 1], rising"),+ rate: z.number().min(0.5).max(2),+});+export type GroupTiming = z.infer<typeof GroupTimingSchema>;++export const TrackSchema = z.object({+ keys: z+ .array(z.object({ t: z.number().min(0).max(60), v: z.number().finite(), ease: z.enum(CURVE_NAMES).optional() }))+ .min(1)+ .max(16)+ .refine((k) => k.every((x, i) => i === 0 || x.t > k[i - 1].t), "Keys in time order"),+ rate: z.number().min(0.5).max(2),+});+export type Track = z.infer<typeof TrackSchema>;++const GroupId = z.string().regex(/^[a-z0-9-]+$/).max(32);+const TrackIdSchema = z.enum(TRACK_IDS as [TrackId, ...TrackId[]]);+export const RecipeSchema = z.object({v: z.literal(1),scene: z.string().regex(/^[a-z0-9-]+\/[a-z0-9-]+$/).max(80),seed: z.number().int().min(0).max(2 ** 31 - 1),- size: z.union([z.enum(["9:16", "1:1", "16:9", "4:5"]), z.object({ w: z.number().int().min(64).max(4096), h: z.number().int().min(64).max(4096) })]),- fps: z.union([z.literal(24), z.literal(25), z.literal(30)]),+ /** A preset, or a custom size held to the export sheet's rule (even sides of 256 to 2160, at most 2.4 million pixels). */+ size: z.union([+ z.enum(["9:16", "1:1", "16:9", "4:5"]),+ z.object({ w: z.number().int(), h: z.number().int() }).refine((s) => customSizeProblem(s.w, s.h) === null, { message: "The size" }),+ ]),+ fps: z.union([z.literal(24), z.literal(25), z.literal(30), z.literal(60)]),duration: z.number().min(0.5).max(60),/** The typed words, by field (headline, sub, cta, website, badge…), exactly as typed. */fields: z.record(z.string().max(40), z.string().max(600)),@@ -42,19 +114,84 @@ export const RecipeSchema = z.object({shutter: z.number().min(0).max(360),/** How it was encoded: frame-exact WebCodecs, or the real-time recorder (may drop a frame). */encoder: z.enum(["webcodecs", "recorder"]).optional(),+ /** High: x1.6 the bitrate, always under the size cap. */+ quality: z.enum(["standard", "high"]).optional(),}),+ /** The motion's feel (a curve set) and its pace (over the Easy Pace choice; above 1 is calmer). */+ motion: z.object({ curves: z.enum(CURVE_SET_IDS).optional(), pace: z.number().min(0.7).max(1.4).optional() }).optional(),+ /** A grade and grain over the finished frame. */+ finish: z+ .object({ contrast: z.number().min(-0.5).max(0.5).optional(), saturation: z.number().min(-1).max(1).optional(), grain: z.number().min(0).max(0.1).optional(), grainSize: z.number().min(1).max(3).optional() })+ .optional(),+ /** An extra camera on top of the scene's own. */+ camera: z.object({ move: z.enum(CAMERA_MOVES).optional(), amount: z.number().min(0).max(2).optional(), breath: z.number().min(0).max(2).optional() }).optional(),+ look: z.object({ light: z.boolean().optional() }).optional(),+ /** Motion groups retimed: a warp and a rate per group. */+ groups: z+ .record(GroupId, GroupTimingSchema)+ .refine((g) => Object.keys(g).length <= 12, "At most 12 groups")+ .optional(),+ /** Parameter tracks on the numbers the scene wrappers own. */+ tracks: z+ .partialRecord(TrackIdSchema, TrackSchema)+ .superRefine((tr, ctx) => {+ for (const [id, t] of Object.entries(tr) as [TrackId, Track | undefined][]) {+ if (!t) continue;+ const [lo, hi] = TRACK_LIMITS[id];+ if (t.keys.some((k) => k.v < lo - 1e-9 || k.v > hi + 1e-9)) ctx.addIssue({ code: "custom", path: [id], message: "A value out of range" });+ }+ })+ .optional(),+ /** Layers under the scene: the person's own clip. */+ layers: z+ .object({+ video: z.object({ src: Clip, from: z.number().min(0).max(600), fit: z.enum(["cover", "contain"]), dim: z.number().min(0).max(0.8), scrim: z.enum(["none", "bottom", "top", "full"]) }).optional(),+ })+ .optional(),});export type Recipe = z.infer<typeof RecipeSchema>;+export type VideoLayer = NonNullable<NonNullable<Recipe["layers"]>["video"]>;export const DEFAULT_EXPORT: Recipe["export"] = { format: "mp4", blurSamples: 8, shutter: 180 };-/** A recipe checked and held to its scene's length limits; throws on a bad one. */-export function normalizeRecipe(input: unknown, limits?: { min: number; max: number }): Recipe {+/** What a scene takes, for normalizeRecipe to drop the rest (kinetic-catalog.ts gives it per scene). */+export interface RecipeScope {+ /** Whether the scene takes a clip under its words. */+ clip: boolean;+ /** Its motion group ids (camera groups included). */+ groups: readonly string[];+}++/**+ * A recipe checked and held to its scene's length limits; throws on a bad one. With a scope it also drops what the scene+ * doesn't take (a clip, unknown group ids, the clip's dim track without a clip), never failing for them, so an old+ * saved recipe still opens after a scene changes.+ */+export function normalizeRecipe(input: unknown, limits?: { min: number; max: number }, scope?: RecipeScope): Recipe {const r = RecipeSchema.parse(input);if (JSON.stringify(r).length > RECIPE_MAX_BYTES) throw new Error("This recipe is too big");const duration = limits ? Math.min(limits.max, Math.max(limits.min, r.duration)) : r.duration;- return { ...r, duration };+ const out: Recipe = { ...r, duration };+ if (!scope) return out;+ if (out.layers?.video && !scope.clip) {+ const rest = { ...out.layers };+ delete rest.video;+ if (Object.keys(rest).length) out.layers = rest;+ else delete out.layers;+ }+ if (out.groups) {+ const keep = Object.entries(out.groups).filter(([id]) => scope.groups.includes(id));+ if (keep.length) out.groups = Object.fromEntries(keep);+ else delete out.groups;+ }+ if (out.tracks?.["clip.dim"] && !out.layers?.video) {+ const rest = { ...out.tracks };+ delete rest["clip.dim"];+ if (Object.keys(rest).length) out.tracks = rest;+ else delete out.tracks;+ }+ return out;}/** JSON with keys in a fixed order, so equal recipes write the same text. */diff --git a/src/lib/motion/scene.ts b/src/lib/motion/scene.tsindex 9845208c..13e83eea 100644--- a/src/lib/motion/scene.ts+++ b/src/lib/motion/scene.ts@@ -38,6 +38,8 @@ export interface SceneInput {images?: Record<string, { w: number; h: number }>;/** A cut-out picture's outline by key (traced from its transparency; null: it has none, so it gets a frame). */outlines?: Record<string, Outline | null>;+ /** The person's clips by key ("clip"): their size and length, known before planning (Kinetic's video layer). */+ clips?: Record<string, { w: number; h: number; duration: number }>;}/** A cut-out's outer edge, traced from its transparency (outline.ts), in the traced grid's units. */diff --git a/src/lib/motion/scenes/end-card/shared.ts b/src/lib/motion/scenes/end-card/shared.tsindex 368f352b..638538af 100644--- a/src/lib/motion/scenes/end-card/shared.ts+++ b/src/lib/motion/scenes/end-card/shared.ts@@ -16,6 +16,8 @@ import type { LogoInfo, Scene, SceneInput, ScenePlan } from "../../scene";import { designSize, TILE_CHIPS, tileCover } from "../../sizes";import { frameCount } from "../../time";import { timeline, scaleCues, type Cue, type Timeline } from "../../tween";+import { extraCamera, kineticTiming } from "../../edit";+import { finishAt } from "../../finish";export const END_CARD_VARIANTS = ["draw-on", "rise", "iris", "split", "glint"] as const;export type EndCardVariant = (typeof END_CARD_VARIANTS)[number];@@ -366,13 +368,39 @@ export function endCardScene(variant: EndCardVariant, build: (c: StyleContext) =const own = typeof input.recipe.controls?.template === "string";const ends = Math.max(0.3, ...cued.map((e) => e.start + e.dur));const f = own ? Math.max(1, Math.min(2.4, (last * 0.72) / ends)) : 1;- const tl = timeline(cued.map((e) => ({ ...e, start: Math.round((e.start > 0 ? e.start * f : e.start) * 1e6) / 1e6 })));+ const spread = cued.map((e) => ({ ...e, start: Math.round((e.start > 0 ? e.start * f : e.start) * 1e6) / 1e6 }));+ // Kinetic's editor. Inside another scene (the Kinetic Headline's card) only its group timing and feel apply: the+ // camera, the finish and the tracks belong to the outer scene.+ const recipe = input.recipe;+ const template = recipe.controls?.template;+ const nested = typeof template === "string" && template !== "ms-end-card";+ const timing = kineticTiming(recipe, `end-card/${variant}`, spread, [], last);+ const tl = timeline(timing.events, timing.curves);const settled = Math.min(last, tl.rest);- const still: DisplayList = { w: design.w, h: design.h, background: theme.accent, nodes: restNodes(rest) };+ const locked = !nested && recipe.camera?.move === "locked";+ const breath = nested || locked ? (locked ? 0 : 1) : (recipe.camera?.breath ?? 1);+ const extra = nested ? null : extraCamera(recipe, last);+ const clock = nested ? null : timing.clock;+ const graded = (list: DisplayList, t: number): DisplayList => {+ const finish = nested ? null : finishAt(recipe, t);+ return finish ? { ...list, finish } : list;+ };+ const cx = design.w / 2;+ const cy = design.h / 2;+ const homeExtra = extra?.(last, last, design.w);+ const homeMoved = !!homeExtra && (homeExtra.zoom !== 1 || homeExtra.x !== 0 || homeExtra.y !== 0 || homeExtra.roll !== 0);+ const restList: DisplayList = { w: design.w, h: design.h, background: theme.accent, nodes: homeMoved ? [group(restNodes(rest), { id: "camera", transform: multiply(translate(homeExtra.x, homeExtra.y), about(cx, cy, homeExtra.zoom, homeExtra.roll)) })] : restNodes(rest) };+ const still = graded(restList, last);const drift = curve("drift");const camera = (t: number, nodes: DisplayNode[]): DisplayNode[] => {- const z = CAMERA_FROM + (1 - CAMERA_FROM) * drift(last > 0 ? t / last : 1);- return z >= 1 ? nodes : [group(nodes, { id: "camera", transform: about(design.w / 2, design.h / 2, z) })];+ const tc = clock ? clock(t) : t;+ const u = drift(last > 0 ? tc / last : 1);+ let z = breath === 1 ? CAMERA_FROM + (1 - CAMERA_FROM) * u : 1 - (1 - CAMERA_FROM) * breath + (1 - CAMERA_FROM) * breath * u;+ if (!extra) return z >= 1 ? nodes : [group(nodes, { id: "camera", transform: about(cx, cy, z) })];+ const o = extra(t, tc, design.w);+ z *= o.zoom;+ if (z === 1 && o.x === 0 && o.y === 0 && o.roll === 0) return nodes;+ return [group(nodes, { id: "camera", transform: multiply(translate(o.x, o.y), about(cx, cy, z, o.roll)) })];};return {design,@@ -384,9 +412,9 @@ export function endCardScene(variant: EndCardVariant, build: (c: StyleContext) =overflow: rest.overflow,evaluate: (t) => {if (t >= last) return still;- if (t >= settled) return { ...still, nodes: camera(t, still.nodes) };+ if (t >= settled) return graded({ ...restList, nodes: camera(t, restNodes(rest)) }, t);const f = style.frame(t, tl);- return { w: design.w, h: design.h, background: style.background ?? theme.accent, nodes: [...(f.under ?? []), ...camera(t, f.nodes), ...(f.over ?? [])] };+ return graded({ w: design.w, h: design.h, background: style.background ?? theme.accent, nodes: [...(f.under ?? []), ...camera(t, f.nodes), ...(f.over ?? [])] }, t);},still: (t) => t >= last,};diff --git a/src/lib/motion/scenes/marketing/kinetic-headline.ts b/src/lib/motion/scenes/marketing/kinetic-headline.tsindex 96d98c2f..80dd13fe 100644--- a/src/lib/motion/scenes/marketing/kinetic-headline.ts+++ b/src/lib/motion/scenes/marketing/kinetic-headline.ts@@ -10,7 +10,7 @@ import { group, translate, type DisplayNode, type TextRun } from "../../display"import { sample, type Key } from "../../tween";import drawOn from "../end-card/draw-on";import { glyphTop, lineLeft } from "../end-card/shared";-import { ev, marked, marketingScene, MIN_HEAD, setText, textBlock } from "./kit";+import { ev, groundLight, marked, marketingScene, MIN_HEAD, setText, textBlock } from "./kit";/** The end card's share of the clip. */const CARD = 2.3;@@ -96,6 +96,8 @@ export default marketingScene({const same = typeof cardGround === "string" && cardGround.toLowerCase() === pal.ground.toLowerCase();const R = Math.hypot(design.w, design.h) / 2 + 2;const size = L?.size ?? S * 0.1;+ // The card's ground gets the same slow light and falloff as the words' ground, so it never reads as a flat fill.+ const lit = recipe.look?.light === false ? null : same ? groundLight(c) : typeof cardGround === "string" ? groundLight(c, { ground: cardGround, look: "brand" }) : null;return {events,breath: false,@@ -106,7 +108,11 @@ export default marketingScene({frame(t, P, Lp) {if (t >= T0) {const list = card.evaluate(t >= c.last ? card.rest : t - T0);- return { nodes: [], over: [{ type: "rect", x: 0, y: 0, w: design.w, h: design.h, fill: list.background }, ...list.nodes] };+ const glow = lit ? lit(t) : [];+ // A card that opened out of the middle lights up as it lands; on the scene's own ground the light carries on.+ const fade = same ? 1 : Math.min(1, (t - T0) / 0.5);+ const light: DisplayNode[] = !glow.length ? [] : fade < 1 ? [group(glow, { opacity: fade })] : glow;+ return { nodes: [], over: [{ type: "rect", x: 0, y: 0, w: design.w, h: design.h, fill: list.background }, ...light, ...list.nodes] };}const swatches: DisplayNode[] = [];const runs: TextRun[] = [];diff --git a/src/lib/motion/scenes/marketing/kit.ts b/src/lib/motion/scenes/marketing/kit.tsindex 46ecc143..53cb8c87 100644--- a/src/lib/motion/scenes/marketing/kit.ts+++ b/src/lib/motion/scenes/marketing/kit.ts@@ -14,7 +14,10 @@ import type { Recipe } from "../../recipe";import type { Outline, Scene, SceneInput, ScenePlan } from "../../scene";import { designSize, TILE_CHIPS, tileCover, type SizeSpec } from "../../sizes";import { frameCount, local } from "../../time";-import { DURATION_LIMITS, timeline, type EventKind, type MotionEvent, type StaggerUnit, type Timeline } from "../../tween";+import { DURATION_LIMITS, linearProgress, progress, timeline, type EventKind, type MotionEvent, type StaggerUnit, type Timeline } from "../../tween";+import { extraCamera, kineticTiming, paceOf } from "../../edit";+import { finishAt } from "../../finish";+import { clipLayer, clipNodes, CLIP_GROUND } from "../../video-layer";import { cardColours, lineLeft, lineRun, lineRuns, secondColour, type TextBlock } from "../end-card/shared";export type LookId = "light" | "dark" | "brand";@@ -154,7 +157,7 @@ export const MIN_HEAD = 0.06;export const spread = (c: { room: number; pace: number }, base: number, hi = 2.2): number => Math.max(0.9, Math.min(hi, (c.room / base) * c.pace, c.room / base));/** How much slower (> 1) or quicker the pace is. */-export const paceOf = (controls: Recipe["controls"]): number => (controls?.pace === "calm" ? 1.2 : controls?.pace === "punchy" ? 0.82 : 1);+export { paceOf } from "../../edit";/** An event, its length held to its kind's limits. */export function ev(id: string, kind: EventKind, start: number, dur: number, c: CurveName, g?: { group: string; unit: StaggerUnit }): MotionEvent {@@ -340,13 +343,15 @@ export interface Built {/*** The ground's light: a soft pool of light that drifts slowly across the frame the whole clip long and comes to rest* on the last frame (high and a little off centre), over a gentle falloff to the corners, so a flat ground has depth- * and the frame never stands quite still. On a dark ground the light is the brand's own colour.+ * and the frame never stands quite still. On a dark ground the light is the brand's own colour. A scene can light+ * another ground of its own the same way (`on`: an end card set on the brand colour).*/-function groundLight(c: MarketingContext): (t: number) => DisplayNode[] {- const { design, palette: pal, last } = c;+export function groundLight(c: MarketingContext, on?: { ground: string; look: LookId }): (t: number) => DisplayNode[] {+ const { design, last } = c;+ const pal = on ?? c.palette;const R = Math.max(design.w, design.h) * 0.85;const dark = pal.look === "dark";- const tone = dark ? pal.mark : "#ffffff";+ const tone = dark ? c.palette.mark : "#ffffff";const a = dark ? 0.22 : pal.look === "brand" ? 0.2 : 0.55;const corner = shadowOf(pal.ground, dark ? 0.35 : pal.look === "brand" ? 0.22 : 0.07);const vignette: DisplayNode = { type: "rect", x: 0, y: 0, w: design.w, h: design.h, fill: { kind: "radial", cx: design.w / 2, cy: design.h * 0.42, r0: Math.min(design.w, design.h) * 0.35, r1: Math.hypot(design.w, design.h) * 0.62, stops: [{ at: 0, color: shadowOf(pal.ground, 0) }, { at: 1, color: corner }] } };@@ -400,7 +405,8 @@ export function marketingScene(def: MarketingSceneDef): Scene {safe: safeArea(design, tileCover(recipe)),theme,palette: paletteFor(lookId, theme, recipe.brand.colors),- pace: paceOf(recipe.controls),+ // Kinetic's Pro pace wins over the Easy choice.+ pace: recipe.motion?.pace ?? paceOf(recipe.controls),room: Math.max(1.5, recipe.duration - 1.3),last,wide: design.w / design.h > 1.2,@@ -408,30 +414,51 @@ export function marketingScene(def: MarketingSceneDef): Scene {field: (key, fallback = "") => (recipe.fields[key] ?? fallback).trim(),};const built = def.build(ctx);- const tl: Timeline = timeline(built.events);- const settled = Math.min(last, built.events.filter((e) => e.kind !== "camera").reduce((m, e) => Math.max(m, e.start + e.dur), 0));+ // Kinetic's editor: retimed groups, the motion feel and the camera's clock (the scene as designed without them).+ const timing = kineticTiming(recipe, def.id, built.events, built.cuts ?? [], last);+ const tl: Timeline = timeline(timing.events, timing.curves);+ const settled = Math.min(last, timing.events.filter((e) => e.kind !== "camera").reduce((m, e) => Math.max(m, e.start + e.dur), 0));const drift = curve("drift");- const P = (t: number) => (id: string) => {- const e = tl.byId.get(id);- return e ? curve(e.curve)(local(t, e.start, e.start + e.dur)) : 1;- };- const L = (t: number) => (id: string) => {- const e = tl.byId.get(id);- return e ? local(t, e.start, e.start + e.dur) : 1;- };+ const P = (t: number) => (id: string) => progress(tl, id, t);+ const L = (t: number) => (id: string) => linearProgress(tl, id, t);const cx = design.w / 2;const cy = design.h / 2;- const glow = built.background || built.light === false ? () => [] : groundLight(ctx);+ const clip = clipLayer(input);+ const glow = built.background || built.light === false || recipe.look?.light === false || clip ? () => [] : groundLight(ctx);+ const locked = recipe.camera?.move === "locked";+ const breath = locked ? 0 : (recipe.camera?.breath ?? 1);+ const extra = extraCamera(recipe, last);+ const clock = timing.clock;const draw = (t: number, home: boolean): DisplayList => {const f = built.frame(t, P(t), L(t));let nodes = f.nodes;if (!home) {- const cam = built.camera?.(t) ?? { zoom: 1, x: 0, y: 0 };- const z = (built.breath === false ? 1 : 1 - BREATH + BREATH * drift(last > 0 ? Math.min(1, t / last) : 1)) * cam.zoom;- const m = multiply(translate(cam.x, cam.y), about(cx, cy, z, cam.roll ?? 0));+ const tc = clock ? clock(t) : t;+ const cam = (!locked && built.camera?.(tc)) || { zoom: 1, x: 0, y: 0 };+ const u = drift(last > 0 ? Math.min(1, tc / last) : 1);+ let z = (built.breath === false ? 1 : breath === 1 ? 1 - BREATH + BREATH * u : 1 - BREATH * breath + BREATH * breath * u) * cam.zoom;+ let x = cam.x;+ let y = cam.y;+ let roll = cam.roll ?? 0;+ if (extra) {+ const o = extra(t, tc, design.w);+ z *= o.zoom;+ x += o.x;+ y += o.y;+ roll += o.roll;+ }+ const m = multiply(translate(x, y), about(cx, cy, z, roll));nodes = [group(nodes, { id: "camera", transform: m })];+ } else if (extra) {+ // The last frame keeps the camera tracks' values there, so the still and the poster match it.+ const o = extra(t, t, design.w);+ if (o.zoom !== 1 || o.x !== 0 || o.y !== 0 || o.roll !== 0) nodes = [group(nodes, { id: "camera", transform: multiply(translate(o.x, o.y), about(cx, cy, o.zoom, o.roll)) })];}- return { w: design.w, h: design.h, background: built.background ?? ctx.palette.ground, nodes: [...glow(t), ...(f.under ?? []), ...nodes, ...(f.over ?? [])] };+ const ground = built.background ?? ctx.palette.ground;+ const list: DisplayList = { w: design.w, h: design.h, background: clip ? CLIP_GROUND : ground, nodes: [...(clip ? clipNodes(recipe, clip, design, ctx.palette.ground, t) : []), ...glow(t), ...(f.under ?? []), ...nodes, ...(f.over ?? [])] };+ const finish = finishAt(recipe, t);+ if (finish) list.finish = finish;+ return list;};const still = draw(last, true);return {diff --git a/src/lib/motion/sizes.ts b/src/lib/motion/sizes.tsindex b8f9d42f..9b20b141 100644--- a/src/lib/motion/sizes.ts+++ b/src/lib/motion/sizes.ts@@ -27,8 +27,21 @@ export const TILE_CHIPS = { top: 0.165, bottom: 0.15 } as const;/** Whether a recipe makes a gallery tile's cover (showcaseRecipe with `cover`). */export const tileCover = (r: { controls?: Record<string, unknown> }): boolean => r.controls?.cover === "tile";-/** The fps a clip may be made at (60 comes with the editor). */+/** The fps a clip may be made at (Kinetic's editor also offers 60). */export const FPS_CHOICES = [24, 25, 30] as const;+export const KINETIC_FPS = [24, 25, 30, 60] as const;++/** Kinetic's custom sizes: even sides of 256 to 2160, at most 2,400,000 pixels. */+export const CUSTOM_SIZE = { min: 256, max: 2160, pixels: 2_400_000 } as const;++/** Why a custom size can't be used (null: it can). */+export function customSizeProblem(w: number, h: number): string | null {+ if (!Number.isInteger(w) || !Number.isInteger(h)) return "Use whole numbers";+ if (w % 2 || h % 2) return "Use even numbers";+ if (w < CUSTOM_SIZE.min || h < CUSTOM_SIZE.min || w > CUSTOM_SIZE.max || h > CUSTOM_SIZE.max) return `Each side from ${CUSTOM_SIZE.min} to ${CUSTOM_SIZE.max}`;+ if (w * h > CUSTOM_SIZE.pixels) return "At most 2.4 million pixels";+ return null;+}export const DEFAULT_FPS = 30;/** The pixels an export has. */@@ -55,10 +68,16 @@ export function previewSize(size: SizeSpec): { w: number; h: number } {/** "9:16" for a preset, "720x1280" for a custom size. */export const sizeLabel = (size: SizeSpec): string => (typeof size === "string" ? size : `${Math.round(size.w)}x${Math.round(size.h)}`);-/** Bits a second for an export: 10 Mbps at 1080p and up, 6 Mbps below, capped so the clip stays well under 95 MB. */-export function exportBitrate(size: SizeSpec, duration: number): number {+/**+ * Bits a second for an export: 10 Mbps at 1080p and up, 6 Mbps below (× 1.5 above 30 fps, × 1.6 for High quality),+ * capped so the clip stays well under 95 MB.+ */+export function exportBitrate(size: SizeSpec, duration: number, o: { fps?: number; quality?: "standard" | "high" } = {}): number {const { w, h } = exportSize(size);- const base = Math.min(w, h) >= 1080 ? 10_000_000 : 6_000_000;+ const base = (Math.min(w, h) >= 1080 ? 10_000_000 : 6_000_000) * ((o.fps ?? 30) > 30 ? 1.5 : 1) * (o.quality === "high" ? 1.6 : 1);const cap = Math.floor((0.6 * 95 * 1024 * 1024 * 8) / Math.max(1, duration));- return Math.min(base, cap);+ return Math.round(Math.min(base, cap));}++/** A size preset's name for menus and chips ("Feed 4:5"). */+export const SIZE_LABELS: Record<SizePreset, string> = { "9:16": "Story 9:16", "4:5": "Feed 4:5", "1:1": "Square 1:1", "16:9": "Wide 16:9" };diff --git a/src/lib/motion/tween.ts b/src/lib/motion/tween.tsindex 81933445..a73159a1 100644--- a/src/lib/motion/tween.ts+++ b/src/lib/motion/tween.ts@@ -4,7 +4,7 @@* read at any t. The same events drive the timing checks in the tests and, later, the sound made from motion.*/-import { curve, type CurveName } from "./ease";+import { curve, type CurveName, type Ease } from "./ease";import { local, mix } from "./time";export interface Key {@@ -52,6 +52,8 @@ export interface MotionEvent {/** Events in one staggered group share it, with how they are spaced. */group?: string;unit?: StaggerUnit;+ /** A retimed motion group's clock (Kinetic's editor): plain progress in, warped progress out (never falls). */+ warp?: (u: number) => number;}export interface Timeline {@@ -59,25 +61,34 @@ export interface Timeline {byId: Map<string, MotionEvent>;/** Every element is set by then. */rest: number;+ /** A motion feel's curves, read before the named ones (absent: the curves as designed). */+ curves?: Partial<Record<CurveName, Ease>>;}-export function timeline(events: MotionEvent[]): Timeline {+export function timeline(events: MotionEvent[], curves?: Partial<Record<CurveName, Ease>>): Timeline {const byId = new Map(events.map((e) => [e.id, e]));- return { events, byId, rest: events.reduce((m, e) => Math.max(m, e.start + e.dur), 0) };+ const tl: Timeline = { events, byId, rest: events.reduce((m, e) => Math.max(m, e.start + e.dur), 0) };+ if (curves && Object.keys(curves).length) tl.curves = curves;+ return tl;}+/** The curve a timeline uses for a name (its feel's, else the named one). */+export const curveIn = (tl: Pick<Timeline, "curves">, name: CurveName): Ease => tl.curves?.[name] ?? curve(name);+/** An event's eased progress at `t` (0 before it, 1 after it; an unknown id is done). */export function progress(tl: Timeline, id: string, t: number): number {const e = tl.byId.get(id);if (!e) return 1;- return curve(e.curve)(local(t, e.start, e.start + e.dur));+ const u = local(t, e.start, e.start + e.dur);+ return curveIn(tl, e.curve)(e.warp ? e.warp(u) : u);}-/** An event's plain (linear) progress at `t`. */+/** An event's plain (linear) progress at `t` (a retimed group's warp included). */export function linearProgress(tl: Timeline, id: string, t: number): number {const e = tl.byId.get(id);if (!e) return 1;- return local(t, e.start, e.start + e.dur);+ const u = local(t, e.start, e.start + e.dur);+ return e.warp ? e.warp(u) : u;}/** Limits per kind, in seconds: an entrance 350–700 ms, nothing that moves under 200 ms. */diff --git a/src/lib/motion/video-layer.ts b/src/lib/motion/video-layer.tsnew file mode 100644index 00000000..00afba2d--- /dev/null+++ b/src/lib/motion/video-layer.ts@@ -0,0 +1,58 @@+/**+ * Kinetic's video layer (pure): the person's own clip under a scene's words. It is drawn first, outside the camera (so+ * it never zooms), then a dim and a scrim in the ground colour, then the scene. Frame t shows the clip's picture at+ * `from + t` seconds, held on its last frame when the clip is shorter; a clip at another frame rate is mapped by time.+ */++import { withAlpha, type DisplayNode, type VideoNode } from "./display";+import { trackAt } from "./edit";+import { CLIP_SCENES } from "./kinetic-groups";+import type { Recipe, VideoLayer } from "./recipe";+import type { SceneInput } from "./scene";++/** How far before the clip's end its last frame is held (a seek exactly at the end shows nothing). */+const END_HOLD = 1e-3;++export interface ClipInfo {+ w: number;+ h: number;+ duration: number;+}++/** The clip layer a recipe draws in this scene, with its clip's facts (null: none). */+export function clipLayer(input: SceneInput): { layer: VideoLayer; clip: ClipInfo } | null {+ const layer = input.recipe.layers?.video;+ const clip = input.clips?.clip;+ if (!layer || !clip || !(clip.w > 0 && clip.h > 0) || !CLIP_SCENES.includes(input.recipe.scene)) return null;+ return { layer, clip };+}++/** The clip's box in a frame: cover fills it (cropping), contain shows all of it (bars in the background). */+export function clipBox(clip: { w: number; h: number }, design: { w: number; h: number }, fit: VideoLayer["fit"]): { x: number; y: number; w: number; h: number } {+ const s = fit === "cover" ? Math.max(design.w / clip.w, design.h / clip.h) : Math.min(design.w / clip.w, design.h / clip.h);+ const w = clip.w * s;+ const h = clip.h * s;+ return { x: (design.w - w) / 2, y: (design.h - h) / 2, w, h };+}++/** Seconds into the clip at film time `t`. */+export const clipTime = (layer: Pick<VideoLayer, "from">, clip: Pick<ClipInfo, "duration">, t: number): number => Math.max(0, Math.min(layer.from + Math.max(0, t), clip.duration - END_HOLD));++/** The layer's nodes at `t`: the clip, its dim (a track replaces the slider) and its scrim. */+export function clipNodes(r: Recipe, l: { layer: VideoLayer; clip: ClipInfo }, design: { w: number; h: number }, ground: string, t: number): DisplayNode[] {+ const box = clipBox(l.clip, design, l.layer.fit);+ const video: VideoNode = { type: "video", src: "clip", ...box, time: clipTime(l.layer, l.clip, t) };+ const out: DisplayNode[] = [video];+ const dim = trackAt(r, "clip.dim", t) ?? l.layer.dim;+ if (dim > 0) out.push({ type: "rect", x: 0, y: 0, w: design.w, h: design.h, fill: `rgba(0,0,0,${Math.min(0.8, dim)})` });+ const s = l.layer.scrim;+ if (s === "full") out.push({ type: "rect", x: 0, y: 0, w: design.w, h: design.h, fill: withAlpha(ground, 0.55) });+ else if (s === "bottom" || s === "top") {+ const [y0, y1] = s === "bottom" ? [design.h, design.h * 0.4] : [0, design.h * 0.6];+ out.push({ type: "rect", x: 0, y: 0, w: design.w, h: design.h, fill: { kind: "linear", x0: 0, y0, x1: 0, y1, stops: [{ at: 0, color: withAlpha(ground, 0.88) }, { at: 0.55, color: withAlpha(ground, 0.45) }, { at: 1, color: withAlpha(ground, 0) }] } });+ }+ return out;+}++/** The ground under a clip (contain's bars). */+export const CLIP_GROUND = "#000000";diff --git a/src/lib/nav-icons.ts b/src/lib/nav-icons.tsindex 76780272..0b9f02d1 100644--- a/src/lib/nav-icons.ts+++ b/src/lib/nav-icons.ts@@ -27,6 +27,7 @@ import {Layers,Layers2,LayoutGrid,+ LetterText,Library,LogIn,Megaphone,@@ -93,6 +94,7 @@ export const NAV_ICONS = {Layers,Layers2,LayoutGrid,+ LetterText,Library,LogIn,Megaphone,diff --git a/src/lib/nav-model.ts b/src/lib/nav-model.tsindex c0fa2585..e22459ef 100644--- a/src/lib/nav-model.ts+++ b/src/lib/nav-model.ts@@ -175,6 +175,7 @@ const STUDIOS: NavEntry[] = [// Sell & advertise{ id: "marketing", href: "/marketing", label: "Marketing Studio", short: "Marketing", what: "UGC and product films", kind: "studio", group: "sell", lead: true, goals: ["sell"], keywords: "ugc product ads commercial brand", cover: "app-macroshot-product", icon: "Megaphone", popular: true },{ id: "ads", href: "/ads", label: "Ads Studio", short: "Ads", what: "Campaigns in every size", kind: "studio", group: "sell", goals: ["sell"], keywords: "brand campaign advert banner sizes", cover: "app-billboard-ad", icon: "Target" },+ { id: "kinetic", href: "/kinetic", label: "Fuobe Kinetic Motion", short: "Kinetic", what: "Brand motion graphics", kind: "studio", group: "sell", goals: ["sell", "social"], keywords: "kinetic motion graphics animated text typography titles end card logo sting stat quote", cover: "app-click-to-ad", icon: "LetterText", newUntil: newFor30Days("2026-11-03") },{ id: "mixed-media", href: "/mixed-media", label: "Mixed Media", short: "Mixed Media", what: "Collage, paint and photo", kind: "studio", group: "sell", goals: ["sell", "film"], keywords: "collage paint scrapbook", cover: "effect-magazine", icon: "Shapes" },{ id: "moodboards", href: "/moodboards", label: "Moodboards", short: "Moodboards", what: "Lock a look, reuse it", kind: "studio", group: "sell", goals: ["sell", "people"], keywords: "style references mood look", cover: "app-steal-the-look", icon: "Images" },{ id: "photodump", href: "/photodump", label: "Photodump", short: "Photodump", what: "A photo pack of one person", kind: "studio", group: "sell", goals: ["sell", "people", "social"], keywords: "photo pack character photoshoot", cover: "app-headshot-generator", icon: "Camera" },diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.tsindex b51dd5e6..9ccce972 100644--- a/src/lib/output-actions.ts+++ b/src/lib/output-actions.ts@@ -48,6 +48,7 @@ export type OutputActionId =| "clean-dialogue"| "copy-text"| "view-3d"+ | "remix-kinetic"| "download"| "download-txt"| "download-srt"@@ -113,6 +114,9 @@ const OWNER_ONLY_ACTIONS: ReadonlySet<OutputActionId> = new Set<OutputActionId>(const q = (url: string) => encodeURIComponent(url);+/** The model a Kinetic Motion result records (components/motion/save.ts MOTION_MODEL). */+const KINETIC_MODEL = "local-motion";+/** Every action for output `index` of `g`, in display order. */export function outputActions(g: Generation, index: number, ctx: ActionContext = {}): OutputAction[] {const o = g.outputs[index];@@ -131,6 +135,9 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =const link = (id: OutputActionId, label: string, href: string, placement: OutputAction["placement"] = "menu") => {if (!(ctx.visitor && OWNER_ONLY_ACTIONS.has(id))) out.push({ id, label, href, placement });};+ // A Kinetic Motion result (a clip, a frame, a contact sheet or a version) opens its recipe in the Kinetic editor.+ // A visitor opens only their own (an owner's result shown on a public page would not open for them).+ if (g.modelId === KINETIC_MODEL && g.status === "succeeded" && (!ctx.visitor || !!g.request.account)) link("remix-kinetic", "Remix in Kinetic", `/kinetic?from=${q(g.id)}`, "primary");switch (o.kind) {case "image":if (isVector(g, o)) {diff --git a/src/lib/template-covers.generated.ts b/src/lib/template-covers.generated.tsindex ac1926a2..f9b71c85 100644--- a/src/lib/template-covers.generated.ts+++ b/src/lib/template-covers.generated.ts@@ -36,7 +36,7 @@ export const TEMPLATE_COVERS: Record<string, TemplateCoverEntry> = {"marketing/ms-end-card": {"poster":"/previews/templates/marketing/ms-end-card.jpg?v=a445714e","video":"/previews/templates/marketing/ms-end-card.mp4?v=b706f02c","at":2.458},"marketing/ms-feature-cards": {"poster":"/previews/templates/marketing/ms-feature-cards.jpg?v=0adfaea1","video":"/previews/templates/marketing/ms-feature-cards.mp4?v=db6c688f","at":4.958},"marketing/ms-five-star-quote": {"poster":"/previews/templates/marketing/ms-five-star-quote.jpg?v=5a4d1301","video":"/previews/templates/marketing/ms-five-star-quote.mp4?v=af449d3c","at":4.958},- "marketing/ms-kinetic-headline": {"poster":"/previews/templates/marketing/ms-kinetic-headline.jpg?v=d9ff2197","video":"/previews/templates/marketing/ms-kinetic-headline.mp4?v=aea37133","at":2.167},+ "marketing/ms-kinetic-headline": {"poster":"/previews/templates/marketing/ms-kinetic-headline.jpg?v=b0473175","video":"/previews/templates/marketing/ms-kinetic-headline.mp4?v=911ab1f4","at":2.167},"marketing/ms-logo-sting": {"poster":"/previews/templates/marketing/ms-logo-sting.jpg?v=46c7b096","video":"/previews/templates/marketing/ms-logo-sting.mp4?v=bf3836cc","at":4.958},"marketing/po-retro-sunburst": "4c19058c","marketing/po-riso-bloom": "69f64638",diff --git a/src/server/canvas.ts b/src/server/canvas.tsindex f83c30ee..e11178e3 100644--- a/src/server/canvas.ts+++ b/src/server/canvas.ts@@ -1,5 +1,6 @@import "server-only";import { MAX_KEYS } from "@/lib/camera-path";+import { RECIPE_MAX_BYTES, RecipeSchema } from "@/lib/motion/recipe";import { CameraKeySchema, ExactOrbitSchema } from "./fly-around";import fs from "node:fs";import { nanoid } from "nanoid";@@ -43,6 +44,7 @@ import {type CanvasNodeType,type CanvasPlan,type CanvasRuns,+ type NodeRun,type CanvasSummary,type StepSource,} from "@/lib/catalog/canvas";@@ -113,6 +115,7 @@ const NODE_TYPES = ["layout","camera-path","fly-around",+ "kinetic","output","note",] as const satisfies readonly CanvasNodeType[];@@ -201,6 +204,14 @@ const NodeData = z.object({orbit: ExactOrbitSchema.optional(),keys: z.array(CameraKeySchema).min(1).max(MAX_KEYS).optional(),duration: z.number().min(1).max(15).optional(),+ // Kinetic: its scene and settings as a recipe (one that doesn't read as one is dropped, never refused).+ kinetic: z+ .unknown()+ .transform((v) => {+ const r = RecipeSchema.safeParse(v);+ return r.success && JSON.stringify(r.data).length <= RECIPE_MAX_BYTES ? r.data : undefined;+ })+ .optional(),});const Num = z.number().finite();@@ -371,8 +382,11 @@ function previewOf(runs: CanvasRuns): CanvasSummary["preview"] {`SELECT g.outputs_json FROM generations g WHERE g.id IN (${ids.map(() => "?").join(",")}) AND g.status = 'succeeded' AND g.kind IN ('image','video') AND ${NOT_TRASHED} ORDER BY g.kind = 'image' DESC, g.completed_at DESC LIMIT 1`,).all(...ids) as { outputs_json: string }[];- const o = rows[0] ? (JSON.parse(rows[0].outputs_json) as { url: string; kind: MediaKind }[]).find((x) => x.kind === "image" || x.kind === "video") : undefined;- return o ? { url: o.url, kind: o.kind } : null;+ const o = rows[0] ? (JSON.parse(rows[0].outputs_json) as { url: string; kind: MediaKind; meta?: { poster?: unknown } }[]).find((x) => x.kind === "image" || x.kind === "video") : undefined;+ if (!o) return null;+ // A clip's own poster (a Kinetic clip's last frame) shows on the card instead of its empty first frame.+ const poster = o.kind === "video" && typeof o.meta?.poster === "string" ? o.meta.poster : undefined;+ return { url: o.url, kind: o.kind, ...(poster && { poster }) };}export function listCanvases(): CanvasSummary[] {@@ -689,3 +703,40 @@ export function runCanvas(id: string, opts: RunOptions = {}): RunResult | null {costUsd: Math.round([...spent.values()].reduce((sum, c) => sum + c, 0) * 10000) / 10000,};}++// ---------------------------------------------------------------------------+// Kinetic: runs made in the browser++/** At most this many rows of a Kinetic node are kept as one run. */+export const KINETIC_RUN_ROWS = 50;++export class KineticRunProblem extends Error {+ constructor(+ message: string,+ readonly status: number,+ ) {+ super(message);+ }+}++/**+ * Keeps the run of a Kinetic node (rendered in the owner's browser, each row saved as a result): the node must be a+ * Kinetic node on this canvas, and every id a finished Kinetic Motion result (model local-motion) of the owner's own+ * (an account's run never joins a canvas). Merged into the latest runs, as a server run is.+ */+export function recordKineticRun(id: string, nodeId: string, run: { sig: string; ids: string[]; rows?: string[]; rowSigs?: string[] }): Canvas {+ const canvas = getCanvas(id);+ if (!canvas) throw new KineticRunProblem("Not found", 404);+ const node = canvas.pages.flatMap((p) => p.graph.nodes).find((n) => n.id === nodeId);+ if (!node || node.type !== "kinetic") throw new KineticRunProblem("That isn't a Kinetic node on this canvas", 400);+ if (!run.ids.length || run.ids.length > KINETIC_RUN_ROWS) throw new KineticRunProblem(`A Kinetic run keeps 1 to ${KINETIC_RUN_ROWS} results`, 400);+ const mine = db().prepare(`SELECT 1 FROM generations g WHERE g.id = ? AND g.status = 'succeeded' AND g.model_id = 'local-motion' AND json_extract(g.request_json, '$.account') IS NULL AND ${NOT_TRASHED}`);+ if (run.ids.some((g) => !mine.get(g))) throw new KineticRunProblem("We can't find that.", 404);+ const value: NodeRun = { sig: run.sig, ids: run.ids, at: Date.now(), ...(run.rows && { rows: run.rows }), ...(run.rowSigs && { rowSigs: run.rowSigs }) };+ db().transaction(() => {+ const row = db().prepare("SELECT runs_json FROM canvases WHERE id = ?").get(id) as { runs_json: string } | undefined;+ const merged = { ...(row ? (JSON.parse(row.runs_json) as CanvasRuns) : {}), [nodeId]: value };+ db().prepare("UPDATE canvases SET runs_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(merged), Date.now(), id);+ })();+ return getCanvas(id)!;+}diff --git a/src/server/generations.ts b/src/server/generations.tsindex 5837aab7..8271889b 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -2751,7 +2751,7 @@ export function recordLocalGeneration(input: {title?: string;inputs: GenerationRequest["inputs"];params?: GenerationRequest["params"];- output: { url: string; kind: OutputFile["kind"]; contentType?: string; meta?: { poster: string } };+ output: { url: string; kind: OutputFile["kind"]; contentType?: string; meta?: { poster: string }; width?: number; height?: number };}): Generation {const model = getModel(input.modelId);// A browser tool's own result: the model's local route for this very step (a grade is not recorded as a Relight blend).diff --git a/tests/__snapshots__/home-studios.html b/tests/__snapshots__/home-studios.htmlindex 3b583814..6c5f6850 100644--- a/tests/__snapshots__/home-studios.html+++ b/tests/__snapshots__/home-studios.html@@ -3,7 +3,7 @@<div class="flex items-center justify-between gap-4"><h2 id="home-studios" class="font-heading text-[24px] leading-tight sm:text-[28px]">Studios and tools<span aria-hidden="true" class="ml-2 inline-block rounded-full bg-muted px-2 align-[0.3em] font-sans text-[13px] leading-6 tracking-normal text-muted-foreground tabular-nums">40</span></h2>-<a aria-label="See all 28 studios" class="group relative inline-flex shrink-0 items-center gap-1 text-[13px] text-muted-foreground transition-colors after:absolute after:-inset-x-2 after:-inset-y-3 after:content-[''] hover:text-foreground" href="/studios">See all 28 studios <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-arrow-right size-3.5 transition-transform duration-150 group-hover:translate-x-0.5" aria-hidden="true">+<a aria-label="See all 29 studios" class="group relative inline-flex shrink-0 items-center gap-1 text-[13px] text-muted-foreground transition-colors after:absolute after:-inset-x-2 after:-inset-y-3 after:content-[''] hover:text-foreground" href="/studios">See all 29 studios <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-arrow-right size-3.5 transition-transform duration-150 group-hover:translate-x-0.5" aria-hidden="true"><path d="M5 12h14"></path><path d="m12 5 7 7-7 7">diff --git a/tests/canvas-kinetic.test.ts b/tests/canvas-kinetic.test.tsnew file mode 100644index 00000000..c56e6976--- /dev/null+++ b/tests/canvas-kinetic.test.ts@@ -0,0 +1,134 @@+import { describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import type { CanvasGraph } from "@/lib/catalog/canvas";+import { tempDir } from "./helpers/temp-dir";++// The Canvas "Kinetic" node: its spec, palette entry and icon, the edges it takes and gives, and the owner-only route+// that keeps its browser-made run on the board.++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+vi.setConfig({ testTimeout: 30_000 });++const dir = tempDir("fuobe-canvas-kinetic-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+process.env.FUOBE_ACCOUNT_DISK_FREE_GB = "0.5";+delete process.env.FUOBE_PASSWORD;+const catalog = await import("@/lib/catalog/canvas");+const { PRESET_ICONS } = await import("@/components/preset-icons");+const { ICONS } = await import("@/components/canvas/node-icon");+const auth = await import("@/server/auth");+const { proxy } = await import("@/proxy");+const access = await import("@/lib/guest-access");+const { createCanvas, getCanvas, parseGraph } = await import("@/server/canvas");+const { PUT } = await import("@/app/api/canvases/[id]/runs/[node]/route");+const local = await import("@/app/api/generations/local/route");+const { saveFile } = await import("@/server/storage");+const { recipe } = await import("./helpers/motion");+const { rowRecipe, feedsOf } = await import("@/components/canvas/kinetic-node");++const node = (id: string, type: string, data: Record<string, unknown> = {}, y = 0) => ({ id, type, position: { x: 0, y }, data }) as CanvasGraph["nodes"][number];+const edge = (source: string, target: string, targetHandle: string | null) => ({ id: `${source}-${target}`, source, target, sourceHandle: "out", targetHandle });+const big = recipe("marketing/big-number", { controls: { template: "ms-big-number" } });+const star = recipe("marketing/starburst", { controls: { template: "m2-retro-starburst" } });++describe("the Kinetic node", () => {+ it("has its spec, palette entry and icon, and is never run by the server", () => {+ expect(catalog.NODE_SPECS.kinetic).toMatchObject({ type: "kinetic", label: "Kinetic", group: "Generate", icon: "LetterText" });+ expect(catalog.PALETTE.find((p) => p.id === "kinetic")?.keywords).toBe("motion text title animation brand kinetic");+ expect(PRESET_ICONS.LetterText).toBeTruthy();+ expect(ICONS.LetterText).toBeTruthy();+ expect(catalog.GENERATOR_TYPES.has("kinetic")).toBe(false);+ });++ it("takes text, a picture and a clip, and feeds Output nodes only", () => {+ const g: CanvasGraph = { nodes: [node("t", "prompt", { text: "Hi" }), node("i", "image-input", { url: "/api/files/a.png" }), node("v", "video-input", { url: "/api/files/a.mp4" }), node("k", "kinetic", { kinetic: big }), node("s", "kinetic", { kinetic: star }), node("o", "output"), node("m", "model", { mediaKind: "video" })], edges: [] };+ expect(catalog.inputPorts(g.nodes[3]).map((p) => [p.id, p.type])).toEqual([+ ["prompt", "text"],+ ["images", "image"],+ ["video", "video"],+ ]);+ expect(catalog.outputType(g, g.nodes[3])).toBe("video");+ const c = (source: string, target: string, targetHandle: string | null) => catalog.connectionError(g, { source, target, sourceHandle: "out", targetHandle });+ expect(c("t", "k", "prompt")).toBeNull();+ expect(c("i", "k", "images")).toBeNull();+ expect(c("v", "k", "video")).toBeNull();+ expect(c("v", "s", "video")).toBe("This scene doesn't take a clip");+ expect(c("k", "o", "in")).toBeNull();+ expect(c("k", "m", "video")).toBe("Connect Kinetic to an Output node");+ });++ it("is kept with its recipe when the board is saved, and drops a recipe that isn't one", () => {+ const g = parseGraph({ nodes: [node("k", "kinetic", { kinetic: big }), node("x", "kinetic", { kinetic: { nope: 1 } })], edges: [] })!;+ expect(g.nodes[0].data.kinetic).toEqual(big);+ expect(g.nodes[1].data.kinetic).toBeUndefined();+ });++ it("fills field 1 from column 1, field 2 from column 2, with its picture and clip, per row", () => {+ const g: CanvasGraph = {+ nodes: [node("tb", "table", { columns: ["Number", "Caption"], rows: [["3×", "faster close"], ["98%", "on time"], ["", ""]] }), node("i", "image-input", { url: "/api/files/logo.png" }), node("v", "video-input", { url: "/api/files/c.mp4" }), node("k", "kinetic", { kinetic: big })],+ edges: [edge("tb", "k", "prompt"), edge("i", "k", "images"), edge("v", "k", "video")],+ };+ const f = feedsOf(g, "k", () => null);+ expect(f.rows).toEqual([+ ["3×", "faster close"],+ ["98%", "on time"],+ ]);+ const r = rowRecipe(big, f.rows[1], f.image, f.video);+ expect(r.fields).toMatchObject({ stat: "98%", caption: "on time" });+ expect(r.brand.logo).toBe("/api/files/logo.png");+ expect(r.layers?.video?.src).toBe("/api/files/c.mp4");+ // A scene without a clip never takes one.+ expect(rowRecipe(star, null, null, "/api/files/c.mp4").layers).toBeUndefined();+ });+});++describe("PUT /api/canvases/[id]/runs/[node]", () => {+ const MP4 = Buffer.concat([Buffer.from([0, 0, 0, 0x18]), Buffer.from("ftypisom"), Buffer.alloc(200, 1)]);+ async function ownerClip(): Promise<string> {+ auth.setPassword("install password");+ const url = saveFile({ data: MP4, contentType: "video/mp4", name: "k.mp4", source: "upload" }).url;+ const res = await local.POST(+ new Request("http://localhost:3000/api/generations/local", {+ method: "POST",+ headers: { "content-type": "application/json", cookie: `${auth.SESSION_COOKIE}=${auth.createSession().value}` },+ body: JSON.stringify({ feature: "kinetic-canvas", modelId: "local-motion", op: "motion", prompt: "3×", title: "Board · Kinetic · row 1", inputs: {}, params: { extra: { motion: big } }, output: { url, kind: "video", contentType: "video/mp4" } }),+ }),+ );+ expect(res.status).toBe(201);+ return (await res.json()).id;+ }+ const put = (id: string, nodeId: string, body: unknown) => PUT(new Request(`http://localhost/api/canvases/${id}/runs/${nodeId}`, { method: "PUT", body: JSON.stringify(body) }), { params: Promise.resolve({ id, node: nodeId }) } as never);++ it("keeps the owner's own finished Kinetic results on a Kinetic node", async () => {+ const c = createCanvas({ name: "Board", graph: { nodes: [node("k", "kinetic", { kinetic: big }), node("o", "output"), node("p", "prompt", { text: "x" })], edges: [edge("k", "o", "in")] } });+ const a = await ownerClip();+ const b = await ownerClip();+ const r = await put(c.id, "k", { sig: "s", ids: [a, b], rows: [a, b], rowSigs: ["1", "2"] });+ expect(r.status).toBe(200);+ expect(getCanvas(c.id)!.runs.k).toMatchObject({ sig: "s", ids: [a, b], rows: [a, b], rowSigs: ["1", "2"] });+ // Not a Kinetic node, an unknown result, or too many.+ expect((await put(c.id, "p", { sig: "s", ids: [a] })).status).toBe(400);+ expect((await put(c.id, "k", { sig: "s", ids: ["nope"] })).status).toBe(404);+ expect((await put(c.id, "k", { sig: "s", ids: Array.from({ length: 51 }, () => a) })).status).toBe(400);+ expect((await put("missing", "k", { sig: "s", ids: [a] })).status).toBe(404);+ // The rows and their signatures line up with the results, each result once.+ expect((await put(c.id, "k", { sig: "s", ids: [a, a] })).status).toBe(400);+ expect((await put(c.id, "k", { sig: "s", ids: [a, b], rows: [a], rowSigs: ["1", "2"] })).status).toBe(400);+ expect((await put(c.id, "k", { sig: "s", ids: [a, b], rows: [a, b], rowSigs: ["1"] })).status).toBe(400);+ expect((await put(c.id, "k", { sig: "s", ids: [a, b], rows: [b, "x"], rowSigs: ["1", "2"] })).status).toBe(400);+ });++ it("is the owner's: an account gets the library refusal and a guest the sign-up card", async () => {+ process.env.FUOBE_PUBLIC_SIGNUP = "1";+ expect(access.isLibraryChange("PUT", "/api/canvases/abc/runs/k1")).toBe(true);+ const acct = auth.createAccount("[email protected]", "long enough");+ const req = (cookie?: string) => new NextRequest("http://localhost:3000/api/canvases/abc/runs/k1", { method: "PUT", headers: { "content-type": "application/json", ...(cookie && { cookie: `${auth.SESSION_COOKIE}=${cookie}` }) }, body: "{}" });+ const a = proxy(req(auth.createSession(acct.id).value));+ expect(a.status).toBe(403);+ expect((await a.json()).code).toBe("library");+ const g = proxy(req());+ expect(g.status).toBe(401);+ delete process.env.FUOBE_PUBLIC_SIGNUP;+ });+});diff --git a/tests/e2e/kinetic-canvas.mjs b/tests/e2e/kinetic-canvas.mjsnew file mode 100644index 00000000..28a644a1--- /dev/null+++ b/tests/e2e/kinetic-canvas.mjs@@ -0,0 +1,127 @@+// The Canvas "Kinetic" node, end to end (owner). Starts `next dev` on 3542 with a throwaway data folder and Demo mode,+// and uses the system Chrome (WebCodecs H.264). Everything it starts is stopped at the end.+//+// node tests/e2e/kinetic-canvas.mjs [evidence folder]+//+// KINETIC_CANVAS_PORT moves the app.+//+// A Table of 3 rows feeds a Kinetic node (Big Number: column 1 is the number, column 2 the caption), which feeds an+// Output node. Run all renders the 3 rows in the tab and keeps the run on the board (3 Kinetic results, each with its+// row's words); the Output node shows the clip. A second Run all keeps all three unchanged. Editing row 2 renders only+// row 2 again.+import { spawn, execSync } from "node:child_process";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { DESKTOP, launch, root } from "./_browser.mjs";++const PORT = Number(process.env.KINETIC_CANVAS_PORT ?? 3542);+const APP = `http://127.0.0.1:${PORT}`;+const out = path.resolve(process.argv[2] ?? fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-kinetic-canvas-")));+fs.mkdirSync(out, { recursive: true });+const data = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-kinetic-canvas-data-"));+const PASSWORD = "owner password for the kinetic canvas";++const failures = [];+const check = (ok, what) => {+ console.log(`${ok ? "ok " : "FAIL"} ${what}`);+ if (!ok) failures.push(what);+};+const wait = (ms) => new Promise((r) => setTimeout(r, ms));++const log = fs.openSync(path.join(out, "server.log"), "w");+const server = spawn(process.execPath, [path.join(root, "node_modules/next/dist/bin/next"), "dev", "-p", String(PORT), "-H", "127.0.0.1"], {+ cwd: root,+ env: { ...process.env, NODE_ENV: "development", FUOBE_DATA_DIR: data, FUOBE_PASSWORD: PASSWORD, FUOBE_DEMO_MODE: "on", COMFYUI_URL: "http://127.0.0.1:9", OLLAMA_URL: "http://127.0.0.1:9", LMSTUDIO_URL: "http://127.0.0.1:9", UNSLOTH_URL: "http://127.0.0.1:9", FUOBE_ACCOUNT_DISK_FREE_GB: "0.5" },+ stdio: ["ignore", log, log],+});+const stop = () => {+ try {+ if (process.platform === "win32") execSync(`taskkill /pid ${server.pid} /T /F`, { stdio: "ignore" });+ else server.kill("SIGTERM");+ } catch {}+};++const api = async (route, { method = "GET", body, cookie } = {}) => {+ const res = await fetch(APP + route, { method, headers: { Origin: APP, "Content-Type": "application/json", ...(cookie && { cookie }) }, ...(body !== undefined && { body: JSON.stringify(body) }) });+ return { status: res.status, json: await res.json().catch(() => null), headers: res.headers };+};++const node = (id, type, data, x, y) => ({ id, type, position: { x, y }, data });+const edge = (source, target, targetHandle) => ({ id: `e-${source}-${target}`, source, target, sourceHandle: "out", targetHandle });++let browser;+try {+ for (let i = 0; i < 300; i++) {+ try {+ if ((await fetch(`${APP}/login`)).status < 500) break;+ } catch {}+ await wait(1000);+ }+ const owner = /fuobe_session=[^;]+/.exec((await api("/api/auth/login", { method: "POST", body: { password: PASSWORD } })).headers.get("set-cookie") ?? "")?.[0];+ check(!!owner, "owner signs in");+ const graph = {+ nodes: [+ node("tb", "table", { columns: ["Number", "Caption"], rows: [["3×", "faster month-end close"], ["98%", "invoices paid on time"], ["2 days", "back every month"]] }, 0, 0),+ node("k", "kinetic", {}, 420, 0),+ node("o", "output", {}, 820, 0),+ ],+ edges: [edge("tb", "k", "prompt"), edge("k", "o", "in")],+ };+ const made = await api("/api/canvases", { method: "POST", cookie: owner, body: { name: "Launch stats", graph } });+ const id = made.json?.id;+ check(made.status < 300 && !!id, `the canvas is made (${made.status})`);+ browser = await launch({ channel: "chrome" });+ const ctx = await browser.newContext({ ...DESKTOP, baseURL: APP });+ const [n, v] = owner.split("=");+ await ctx.addCookies([{ name: n, value: v, url: APP }]);+ const page = await ctx.newPage();+ const errors = [];+ page.on("pageerror", (e) => errors.push(e.message));+ await page.goto(`/canvas/${id}`, { waitUntil: "load", timeout: 240_000 });+ await page.locator("[data-kinetic-node-run]").waitFor({ timeout: 120_000 });+ await page.waitForTimeout(2500);+ await page.screenshot({ path: path.join(out, "board-before.png") });++ const runAll = async () => {+ const kept = page.waitForResponse((r) => /\/api\/canvases\/[^/]+\/runs\/k$/.test(r.url()) && r.request().method() === "PUT", { timeout: 300_000 });+ await page.getByRole("button", { name: "Run all", exact: true }).first().click();+ const r = await kept;+ check(r.status() === 200, `the run is kept on the board (${r.status()})`);+ await page.waitForTimeout(1500);+ return (await api(`/api/canvases/${id}`, { cookie: owner })).json;+ };++ const first = await runAll();+ const run1 = first?.canvas?.runs?.k;+ check(run1?.ids?.length === 3 && new Set(run1.ids).size === 3, `Run all renders 3 rows (${JSON.stringify(run1?.ids)})`);+ const gens = new Map((first?.generations ?? []).map((g) => [g.id, g]));+ check(+ run1?.ids?.every((g, i) => gens.get(g)?.modelId === "local-motion" && gens.get(g)?.feature === "kinetic-canvas" && gens.get(g)?.request?.params?.extra?.motion?.fields?.stat === graph.nodes[0].data.rows[i][0]),+ "each row is a Kinetic result with its row's number",+ );+ check(await page.locator('[data-testid="canvas-node-o"] video, [data-testid="canvas-node-o"] img').first().waitFor({ timeout: 30_000 }).then(() => true, () => false), "the Output node shows the clip");+ const poster = await page.locator('[data-testid="canvas-node-o"] video').first().getAttribute("poster").catch(() => null);+ check(!!poster && poster.startsWith("/api/files/"), `the Output node's clip shows its poster, not an empty first frame (${poster})`);+ await page.screenshot({ path: path.join(out, "board-after-run.png") });++ const second = await runAll();+ check(JSON.stringify(second?.canvas?.runs?.k?.ids) === JSON.stringify(run1?.ids), "a second Run all keeps all three");++ const cell = page.getByRole("textbox", { name: "Row 2, Number" });+ await cell.fill("99%");+ await page.waitForTimeout(1200);+ const third = await runAll();+ const ids3 = third?.canvas?.runs?.k?.ids ?? [];+ check(ids3[0] === run1?.ids?.[0] && ids3[2] === run1?.ids?.[2] && ids3[1] !== run1?.ids?.[1], `editing row 2 renders only row 2 (${JSON.stringify(ids3)})`);+ check(errors.length === 0, `no page errors (${JSON.stringify(errors.slice(0, 3))})`);+} catch (e) {+ failures.push(`crashed: ${e?.stack ?? e}`);+ console.error(e);+} finally {+ await browser?.close().catch(() => {});+ stop();+}+fs.writeFileSync(path.join(out, "e2e-result.json"), JSON.stringify({ failures }, null, 2));+console.log(failures.length ? `\n${failures.length} failed` : "\nall passed");+process.exit(failures.length ? 1 : 0);diff --git a/tests/e2e/kinetic-page.mjs b/tests/e2e/kinetic-page.mjsnew file mode 100644index 00000000..027df26e--- /dev/null+++ b/tests/e2e/kinetic-page.mjs@@ -0,0 +1,446 @@+// The Kinetic page (/kinetic), end to end. Starts `next dev` on 3540 with a throwaway data folder, the owner's password,+// public sign-up on, Demo mode on and a stand-in fal.ai on 3541 for an account's own key. Uses the system Chrome+// (WebCodecs H.264) and ffmpeg (a fixture clip, and reading frames back). Everything it starts is stopped at the end.+//+// node tests/e2e/kinetic-page.mjs [evidence folder]+//+// KINETIC_PORT moves the app (and the stand-in to the next port).+//+// Guest (390 and 1440, light and dark): the opening screen shows the four examples and the ten scenes; an example opens+// the editor and its preview plays; Easy and Pro work; a Motion preset reads "Custom" after a slider move, and Undo and+// Redo bring it back and forth; Save, Save frame and Save version each open the sign-up card before any upload.+// Owner: Big Number with the Film look, a Slow push and a retimed group, saved at 60 fps (its MP4 has duration × 60+// frames, its recipe in params.extra.motion), a frame and a contact sheet as PNG results of the export size, a version+// restored after a change (it asks first, and Undo brings the change back), and Remix in Kinetic opening the same recipe.+// Account with a stand-in key: saves to its own runs (never the owner's Library), uploads its own clip and saves Kinetic+// Headline over it. Account with neither: saves a clip, a frame and a version with the Kinetic header; "Upload a clip"+// opens the Connect card; it picks its earlier Kinetic clip as the clip layer and saves. Frame-exact clip: a 2 s, 30 fps+// fixture whose frame i is a flat grey that encodes i, saved under Big Number at 30 fps, and at 24 fps from 0.5 s; each+// output frame i shows source frame floor((from + i / fps) × 30). Reduced motion: no autoplay. Layout: no sideways scroll+// (picker, editor, each sheet open), controls at least 44 px, no page errors.+import { spawn, execFileSync, execSync } from "node:child_process";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { DESKTOP, launch, PHONE, root } from "./_browser.mjs";+import { startFakeFal } from "../helpers/fake-cloud.ts";++const PORT = Number(process.env.KINETIC_PORT ?? 3540);+const APP = `http://127.0.0.1:${PORT}`;+const out = path.resolve(process.argv[2] ?? fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-kinetic-page-")));+fs.mkdirSync(out, { recursive: true });+const data = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-kinetic-page-data-"));+const PASSWORD = "owner password for the kinetic page";+const ACCT_FAL = "acct-kinetic-key:acct-kinetic-secret";+const FFMPEG = process.env.FFMPEG ?? "ffmpeg";++const failures = [];+const notes = [];+const check = (ok, what) => {+ console.log(`${ok ? "ok " : "FAIL"} ${what}`);+ if (!ok) failures.push(what);+};+const note = (s) => {+ console.log(`note ${s}`);+ notes.push(s);+};+const wait = (ms) => new Promise((r) => setTimeout(r, ms));++const fal = await startFakeFal(PORT + 1);+fal.keys[ACCT_FAL] = "good";+const log = fs.openSync(path.join(out, "server.log"), "w");+const server = spawn(process.execPath, [path.join(root, "node_modules/next/dist/bin/next"), "dev", "-p", String(PORT), "-H", "127.0.0.1"], {+ cwd: root,+ env: {+ ...process.env,+ NODE_ENV: "development",+ FUOBE_DATA_DIR: data,+ FUOBE_PASSWORD: PASSWORD,+ FUOBE_PUBLIC_SIGNUP: "1",+ FUOBE_DEMO_MODE: "on",+ FUOBE_DEV_FAL_URL: fal.url,+ COMFYUI_URL: "http://127.0.0.1:9",+ OLLAMA_URL: "http://127.0.0.1:9",+ LMSTUDIO_URL: "http://127.0.0.1:9",+ UNSLOTH_URL: "http://127.0.0.1:9",+ FUOBE_ACCOUNT_DISK_FREE_GB: "0.5",+ },+ stdio: ["ignore", log, log],+});+async function stopAll() {+ try {+ if (process.platform === "win32") execSync(`taskkill /pid ${server.pid} /T /F`, { stdio: "ignore" });+ else server.kill("SIGTERM");+ } catch {}+ await fal.close();+}++const api = async (route, { method = "GET", body, cookie } = {}) => {+ const res = await fetch(APP + route, { method, headers: { Origin: APP, "Content-Type": "application/json", ...(cookie && { cookie }) }, ...(body !== undefined && { body: JSON.stringify(body) }) });+ const buf = Buffer.from(await res.arrayBuffer());+ let json = null;+ try {+ json = JSON.parse(buf.toString("utf8"));+ } catch {}+ return { status: res.status, json, buf, headers: res.headers };+};+/** Uploads a file as the owner (the normal upload). */+async function upload(file, type, cookie) {+ const fd = new FormData();+ fd.append("file", new Blob([fs.readFileSync(file)], { type }), path.basename(file));+ const res = await fetch(APP + "/api/uploads", { method: "POST", headers: { Origin: APP, cookie }, body: fd });+ return { status: res.status, json: await res.json().catch(() => null) };+}+const cookieOf = (res) => /fuobe_session=[^;]+/.exec(res.headers.get("set-cookie") ?? "")?.[0];+const mp4Frames = (buf) => {+ const i = buf.indexOf(Buffer.from("stsz"));+ return i < 0 ? -1 : buf.readUInt32BE(i + 12);+};+const pngSize = (buf) => (buf.subarray(1, 4).toString() === "PNG" ? { w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) } : null);+const MAIN = 'canvas[data-kinetic-player="main"]';+const pixels = (page) => page.evaluate((sel) => document.querySelector(sel)?.toDataURL() ?? "", MAIN);+const recipeKeyOf = (page) => page.locator("[data-recipe-key]").first().getAttribute("data-recipe-key");++/** Closes every open dialog, sheet and card. */+async function closeAll(page) {+ for (let i = 0; i < 4 && (await page.locator('[role="dialog"]:visible, [role="alertdialog"]:visible, [data-kinetic-sheet=group]:visible').count()); i++) {+ await page.keyboard.press("Escape");+ await page.waitForTimeout(350);+ }+}++async function openEditor(page, href) {+ await page.goto(href, { waitUntil: "load", timeout: 240_000 });+ await page.locator(MAIN).waitFor({ timeout: 120_000 });+ await page.waitForTimeout(1500);+}++/** No sideways scroll, and (in the editor) every visible control at least 44 px. */+async function layout(page, who, what, controls = true) {+ const sideways = await page.evaluate(() => document.scrollingElement.scrollWidth - window.innerWidth);+ check(sideways <= 0, `${who} ${what}: no sideways scroll (${sideways} px)`);+ if (!controls) return;+ const small = await page.$$eval("[data-kinetic-editor] button, [data-kinetic-editor] input:not([type=color]):not([type=file]):not(.sr-only), [data-kinetic-editor] select, [data-kinetic-editor] textarea, [data-kinetic-sheet] button, [data-kinetic-sheet] input:not(.sr-only)", (els) =>+ els+ .filter((e) => e.getClientRects().length && !e.closest(".group\\/slot") && !e.closest("[data-kinetic-made]"))+ .map((e) => {+ const r = e.getBoundingClientRect();+ return [e.getAttribute("aria-label") || e.textContent?.trim().slice(0, 24) || e.tagName, Math.round(Math.min(r.height, r.width < 44 && e.tagName === "BUTTON" ? r.width : r.height))];+ })+ .filter(([, h]) => h < 44),+ );+ check(small.length === 0, `${who} ${what}: every control at least 44 px (${JSON.stringify(small.slice(0, 8))})`);+}++/** The grey a fixture frame shows, read from an output MP4 at frame i (ffmpeg, the top-left 8 × 8 block). */+function greyAt(file, i) {+ const raw = execFileSync(FFMPEG, ["-hide_banner", "-loglevel", "error", "-i", file, "-vf", `select=eq(n\\,${i}),crop=8:8:2:2,scale=1:1`, "-vsync", "0", "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "gray", "-"]);+ return raw[0];+}++const timings = {};+let browser;+const pageErrors = [];+try {+ for (let i = 0; i < 300; i++) {+ try {+ const r = await fetch(`${APP}/login`);+ if (r.status < 500) break;+ } catch {}+ await wait(1000);+ }+ const owner = cookieOf(await api("/api/auth/login", { method: "POST", body: { password: PASSWORD } }));+ check(!!owner, "owner signs in");+ browser = await launch({ channel: "chrome" });+ const withCookie = async (cookie, opts) => {+ const ctx = await browser.newContext({ ...opts, baseURL: APP });+ if (cookie) {+ const [n, v] = cookie.split("=");+ await ctx.addCookies([{ name: n, value: v, url: APP }]);+ }+ return ctx;+ };+ const watch = (page, who) => page.on("pageerror", (e) => pageErrors.push(`${who}: ${e.message}`));++ // ---- Guest: phone dark, desktop light.+ for (const [name, opts] of [+ ["390", { ...PHONE, colorScheme: "dark" }],+ ["1440", { ...DESKTOP, colorScheme: "light" }],+ ]) {+ const ctx = await withCookie(null, opts);+ const gp = await ctx.newPage();+ watch(gp, `guest ${name}`);+ let uploads = 0;+ gp.on("request", (r) => r.url().includes("/api/uploads") && uploads++);+ await gp.goto("/kinetic", { waitUntil: "load", timeout: 240_000 });+ await gp.locator("[data-kinetic-picker]:visible").first().waitFor({ timeout: 120_000 });+ check((await gp.locator("[data-kinetic-examples] [data-kinetic-tile]").count()) === 4, `guest ${name}: four examples`);+ check((await gp.locator("[data-kinetic-scenes] [data-kinetic-tile]").count()) === 10, `guest ${name}: all ten scenes`);+ check((await gp.locator("[data-kinetic-made-strip]").count()) === 0, `guest ${name}: no Made in Kinetic strip`);+ await layout(gp, `guest ${name}`, "picker", false);+ await gp.screenshot({ path: path.join(out, `guest-picker-${name}.png`), fullPage: true });+ await gp.locator("[data-kinetic-examples] [data-kinetic-tile=big-number]").click();+ await gp.locator(MAIN).waitFor({ timeout: 120_000 });+ await gp.waitForTimeout(1200);+ const a = await pixels(gp);+ await gp.waitForTimeout(450);+ check(a !== (await pixels(gp)), `guest ${name}: the example opens and its preview plays`);+ check(/scene=big-number/.test(gp.url()), `guest ${name}: the address names the scene`);+ await layout(gp, `guest ${name}`, "editor (Easy)");+ await gp.getByRole("radio", { name: "Pro", exact: true }).click();+ await gp.getByRole("radio", { name: /^Snappy Quick/ }).click();+ const snappy = await recipeKeyOf(gp);+ check(await gp.locator('[data-kinetic-presets=motion] [role=radio][aria-checked=true]').filter({ hasText: "Snappy" }).count() === 1, `guest ${name}: the Snappy preset is picked`);+ await gp.getByRole("textbox", { name: "Pace value" }).fill("1.3");+ await gp.getByRole("textbox", { name: "Pace value" }).press("Enter");+ await gp.waitForTimeout(300);+ check(await gp.locator("[data-kinetic-presets=motion] [data-kinetic-custom]").isVisible(), `guest ${name}: a moved slider reads Custom`);+ await gp.getByRole("button", { name: "Undo" }).click();+ check((await recipeKeyOf(gp)) === snappy && !(await gp.locator("[data-kinetic-presets=motion] [data-kinetic-custom]").isVisible()), `guest ${name}: Undo brings the preset back`);+ await gp.getByRole("button", { name: "Redo" }).click();+ check(await gp.locator("[data-kinetic-presets=motion] [data-kinetic-custom]").isVisible(), `guest ${name}: Redo makes it Custom again`);+ await layout(gp, `guest ${name}`, "editor (Pro)");+ await gp.screenshot({ path: path.join(out, `guest-editor-pro-${name}.png`) });+ // The three saves each ask first.+ await gp.locator("[data-kinetic-save=main]").click();+ check(await gp.getByText(/Create a free account/).first().waitFor({ timeout: 10_000 }).then(() => true, () => false), `guest ${name}: Save opens the sign-up card`);+ await closeAll(gp);+ await gp.getByRole("button", { name: "Export options" }).click();+ await gp.locator("[data-kinetic-sheet=export]").waitFor();+ await layout(gp, `guest ${name}`, "export sheet");+ await gp.screenshot({ path: path.join(out, `guest-export-${name}.png`) });+ await gp.locator("[data-kinetic-save=frame]").click();+ check(await gp.getByText(/Create a free account/).first().waitFor({ timeout: 10_000 }).then(() => true, () => false), `guest ${name}: Save frame opens the sign-up card`);+ await closeAll(gp);+ await gp.getByRole("button", { name: "More" }).click();+ await gp.getByRole("menuitem", { name: "Versions" }).click();+ await gp.locator("[data-kinetic-sheet=versions]").waitFor();+ await layout(gp, `guest ${name}`, "versions sheet");+ check((await gp.locator("[data-kinetic-versions]").count()) === 0, `guest ${name}: no versions list`);+ await gp.locator("[data-kinetic-save=version]").click();+ check(await gp.getByText(/Create a free account/).first().waitFor({ timeout: 10_000 }).then(() => true, () => false), `guest ${name}: Save version opens the sign-up card`);+ check(uploads === 0, `guest ${name}: nothing uploads`);+ await ctx.close();+ }++ // ---- Reduced motion: nothing autoplays.+ {+ const ctx = await withCookie(null, { ...DESKTOP, reducedMotion: "reduce" });+ const cp = await ctx.newPage();+ watch(cp, "reduced motion");+ await openEditor(cp, "/kinetic?scene=quote");+ const r1 = await pixels(cp);+ await cp.waitForTimeout(800);+ check(r1 === (await pixels(cp)), "reduced motion: the preview holds its rest frame");+ await cp.goto("/kinetic", { waitUntil: "load" });+ await cp.locator("[data-kinetic-picker]:visible").first().waitFor();+ await cp.waitForTimeout(1500);+ const playing = await cp.$$eval("[data-kinetic-picker] video", (vs) => vs.filter((v) => !v.paused).length);+ check(playing === 0, `reduced motion: no tile plays (${playing})`);+ await ctx.close();+ }++ // ---- Owner, desktop: Big Number with the Film look, a Slow push, a retimed group, 60 fps.+ const desk = await withCookie(owner, DESKTOP);+ const op = await desk.newPage();+ watch(op, "owner");+ await openEditor(op, "/kinetic?scene=big-number");+ await op.getByRole("radio", { name: "Pro", exact: true }).click();+ await op.locator("[aria-controls=kinetic-panel-appearance]").click();+ await op.getByRole("radio", { name: /^Film/ }).click();+ await op.locator("[aria-controls=kinetic-panel-camera]").click();+ await op.getByRole("radio", { name: "Push", exact: true }).click();+ await op.locator("[data-kinetic-group=number]").click();+ await op.locator("[data-kinetic-sheet=group]").waitFor();+ await op.getByRole("button", { name: "Ease in", exact: true }).click();+ await op.getByRole("textbox", { name: "Speed value" }).fill("1.5");+ await op.getByRole("textbox", { name: "Speed value" }).press("Enter");+ await layout(op, "owner 1440", "group sheet");+ await op.screenshot({ path: path.join(out, "owner-group-1440.png") });+ await closeAll(op);+ await op.getByRole("button", { name: "Export options" }).click();+ await op.getByRole("radio", { name: "60 fps" }).click();+ const clipKey = await recipeKeyOf(op);+ const t0 = Date.now();+ let rec = op.waitForResponse((r) => r.url().endsWith("/api/generations/local") && r.request().method() === "POST", { timeout: 240_000 });+ await op.locator("[data-kinetic-save=clip]").click();+ let res = await rec;+ check(res.status() === 201, "owner: the 60 fps clip is recorded");+ timings.owner60fpsMs = Date.now() - t0;+ const clip = await res.json();+ const motion = clip.request?.params?.extra?.motion;+ check(motion?.fps === 60 && motion?.finish?.grain > 0 && motion?.camera?.move === "push" && motion?.groups?.number?.rate === 1.5, `owner: its recipe has the Film look, the push and the retimed group (${JSON.stringify({ fps: motion?.fps, finish: motion?.finish, camera: motion?.camera, groups: motion?.groups })})`);+ const lib = await api(`/api/generations?features=kinetic&limit=5`, { cookie: owner });+ check((lib.json?.items ?? []).some((g) => g.id === clip.id), "owner: the Library lists it");+ const file = await api(clip.outputs[0].url, { cookie: owner });+ check(mp4Frames(file.buf) === Math.round(motion.duration * 60), `owner: ${Math.round(motion.duration * 60)} frames at 60 fps (${mp4Frames(file.buf)})`);+ fs.writeFileSync(path.join(out, "owner-big-number-60fps.mp4"), file.buf);+ note(`Big Number ${motion.duration} s at 1080 × 1350, 60 fps, Film: rendered and saved in ${timings.owner60fpsMs} ms`);+ // A frame and a contact sheet.+ for (const kind of ["frame", "sheet"]) {+ rec = op.waitForResponse((r) => r.url().endsWith("/api/generations/local") && r.request().method() === "POST", { timeout: 240_000 });+ await op.locator(`[data-kinetic-save=${kind}]`).click();+ res = await rec;+ const g = await res.json();+ const png = await api(g.outputs?.[0]?.url ?? "/x", { cookie: owner });+ const size = pngSize(png.buf);+ check(res.status() === 201 && g.feature === `kinetic-${kind}` && g.outputs[0].kind === "image" && size?.w === 1080 && size?.h === 1350, `owner: the ${kind} is a 1080 × 1350 PNG result (${JSON.stringify(size)})`);+ fs.writeFileSync(path.join(out, `owner-${kind}.png`), png.buf);+ }+ check(await op.locator("[data-kinetic-saved] li").count() >= 3, "owner: Saved this visit lists them");+ await layout(op, "owner 1440", "export sheet");+ await closeAll(op);+ // A version, a change, and Restore asks first; Undo brings the change back.+ await op.getByRole("button", { name: "More" }).click();+ await op.getByRole("menuitem", { name: "Versions" }).click();+ rec = op.waitForResponse((r) => r.url().endsWith("/api/generations/local") && r.request().method() === "POST", { timeout: 120_000 });+ await op.locator("[data-kinetic-save=version]").click();+ res = await rec;+ check(res.status() === 201 && (await res.json()).feature === "kinetic-version", "owner: the version is saved");+ const versionKey = await recipeKeyOf(op);+ await op.locator("[data-kinetic-restore]").first().waitFor({ timeout: 30_000 });+ await closeAll(op);+ await op.getByRole("radio", { name: "Springy", exact: true }).click();+ const changed = await recipeKeyOf(op);+ check(changed !== versionKey, "owner: a change after the version");+ await op.getByRole("button", { name: "More" }).click();+ await op.getByRole("menuitem", { name: "Versions" }).click();+ await op.locator("[data-kinetic-restore]").first().click();+ check(await op.getByText("Keep what you have?").waitFor({ timeout: 5000 }).then(() => true, () => false), "owner: Restore asks first");+ await op.getByRole("button", { name: "Don't save" }).click();+ await op.waitForTimeout(400);+ check((await recipeKeyOf(op)) === versionKey, "owner: the version is restored");+ await op.getByRole("button", { name: "Undo" }).click();+ check((await recipeKeyOf(op)) === changed, "owner: Undo brings the change back");+ // Remix in Kinetic from the saved clip opens the same recipe.+ await openEditor(op, `/kinetic?from=${clip.id}`);+ check((await recipeKeyOf(op)) === clipKey, "owner: Remix in Kinetic opens the clip's recipe");+ await op.goto("/kinetic", { waitUntil: "load" });+ check(await op.locator("[data-kinetic-made-strip] [data-kinetic-made]").first().waitFor({ timeout: 30_000 }).then(() => true, () => false), "owner: Made in Kinetic lists what it saved");+ await op.screenshot({ path: path.join(out, "owner-picker-1440.png"), fullPage: true });++ // ---- Frame-exact clip under the words: a fixture whose frame i is a flat grey that encodes i.+ const fixture = path.join(out, "fixture-2s-30fps.mp4");+ execFileSync(FFMPEG, ["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "nullsrc=s=320x240:r=30:d=2", "-vf", "geq=lum='16+4*N':cb=128:cr=128,format=yuv420p", "-c:v", "libx264", "-qp", "0", "-g", "1", fixture]);+ const up = await upload(fixture, "video/mp4", owner);+ const fixtureUrl = up.json?.url;+ check(!!fixtureUrl, `owner: the fixture clip uploads (${up.status})`);+ // A picture to record the fixture's recipes with as versions (opened through Remix in Kinetic): a version is the rest+ // frame with 540 px on its long side, and the server takes only that size.+ const still = path.join(out, "fixture-still.png");+ const VERSION_SIZE = { "9:16": "304x540", "4:5": "432x540", "1:1": "540x540", "16:9": "540x304" };+ execFileSync(FFMPEG, ["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", `color=c=black:s=${VERSION_SIZE[motion.size] ?? "432x540"}`, "-frames:v", "1", still]);+ const stillUrl = (await upload(still, "image/png", owner)).json?.url;+ for (const [fps, from] of [+ [30, 0],+ [24, 0.5],+ [60, 0],+ ]) {+ const base = { ...motion, fps, duration: 5, finish: undefined, camera: undefined, groups: undefined, layers: { video: { src: fixtureUrl, from, fit: "cover", dim: 0, scrim: "none" } }, export: { format: "mp4", blurSamples: 1, shutter: 0 } };+ const g = await api("/api/generations/local", { method: "POST", cookie: owner, body: { feature: "kinetic-version", modelId: "local-motion", op: "motion", prompt: "fixture", title: `Fixture ${fps}`, inputs: {}, params: { extra: { motion: base } }, output: { url: stillUrl, kind: "image", contentType: "image/png" } } });+ check(g.status === 201, `fixture recipe at ${fps} fps recorded (${g.status} ${JSON.stringify(g.json?.error ?? "")})`);+ await openEditor(op, `/kinetic?from=${g.json?.id}`);+ rec = op.waitForResponse((r) => r.url().endsWith("/api/generations/local") && r.request().method() === "POST", { timeout: 240_000 });+ const t0 = Date.now();+ await op.locator("[data-kinetic-save=main]").click();+ res = await rec;+ note(`Big Number 5 s over a clip at ${fps} fps: rendered and saved in ${Date.now() - t0} ms`);+ const made = await res.json();+ const mp4 = path.join(out, `clip-over-fixture-${fps}fps.mp4`);+ fs.writeFileSync(mp4, (await api(made.outputs[0].url, { cookie: owner })).buf);+ const bad = [];+ for (const i of [0, 1, 2, 5, 9, 14, 20, 29, 40]) {+ // Source frame n is luma 16 + 4n in video range, which reads back as full-range grey 4n × 255 / 219.+ const n = Math.min(59, Math.floor((from + i / fps) * 30 + 1e-6));+ const want = Math.round(Math.min(255, (4 * n * 255) / 219));+ const got = greyAt(mp4, i);+ if (Math.abs(got - want) > 3) bad.push({ i, n, want, got });+ }+ check(bad.length === 0, `frame-exact at ${fps} fps from ${from} s: every checked frame shows its source frame (${JSON.stringify(bad)})`);+ }+ await desk.close();++ // ---- Account with a stand-in key: its own runs, its own clip under Kinetic Headline.+ const acct = cookieOf(await api("/api/auth/signup", { method: "POST", body: { email: "[email protected]", password: "account password" } }));+ check((await api("/api/account/keys/fal", { method: "PUT", cookie: acct, body: { key: ACCT_FAL } })).status === 200, "the account adds its own key");+ {+ const ctx = await withCookie(acct, { ...PHONE, colorScheme: "light" });+ const ap = await ctx.newPage();+ watch(ap, "account");+ await openEditor(ap, "/kinetic?scene=kinetic-headline");+ await ap.getByRole("button", { name: "Pick a clip" }).click();+ await ap.locator("[data-kinetic-sheet=clip]").waitFor();+ const chooser = ap.waitForEvent("filechooser");+ await ap.locator("[data-kinetic-upload-clip]").click();+ await (await chooser).setFiles(fixture);+ await ap.locator("[data-kinetic-clip-control] video").first().waitFor({ timeout: 60_000 });+ await ap.waitForTimeout(1500);+ await layout(ap, "account 390", "editor with a clip");+ await ap.screenshot({ path: path.join(out, "account-headline-over-clip-390.png"), fullPage: true });+ rec = ap.waitForResponse((r) => r.url().endsWith("/api/generations/local") && r.request().method() === "POST", { timeout: 240_000 });+ await ap.locator("[data-kinetic-save=main]").click();+ res = await rec;+ const g = await res.json();+ check(res.status() === 201 && g.request?.params?.extra?.motion?.layers?.video?.src?.startsWith("/api/files/") && g.request?.inputs?.video === g.request.params.extra.motion.layers.video.src, "account with a key: Kinetic Headline over its own clip is saved");+ const mine = await api("/api/generations?features=kinetic&limit=10", { cookie: acct });+ const owners = await api("/api/generations?features=kinetic&limit=50", { cookie: owner });+ check((mine.json?.items ?? []).some((x) => x.id === g.id) && !(owners.json?.items ?? []).some((x) => x.id === g.id), "account with a key: in its own runs, never the owner's Library");+ await ctx.close();+ }++ // ---- Account with neither a GPU nor a key.+ const bare = cookieOf(await api("/api/auth/signup", { method: "POST", body: { email: "[email protected]", password: "account password" } }));+ {+ const ctx = await withCookie(bare, DESKTOP);+ const bp = await ctx.newPage();+ watch(bp, "bare account");+ const marks = [];+ bp.on("request", (r) => r.url().endsWith("/api/uploads") && r.method() === "POST" && marks.push(r.headers()["x-fuobe-kinetic"] ?? ""));+ await openEditor(bp, "/kinetic?scene=big-number");+ for (const kind of ["main", "frame", "version"]) {+ if (kind === "frame") {+ await bp.getByRole("button", { name: "Export options" }).click();+ }+ if (kind === "version") {+ await closeAll(bp);+ await bp.getByRole("button", { name: "More" }).click();+ await bp.getByRole("menuitem", { name: "Versions" }).click();+ }+ rec = bp.waitForResponse((r) => r.url().endsWith("/api/generations/local") && r.request().method() === "POST", { timeout: 240_000 });+ await bp.locator(`[data-kinetic-save=${kind}]`).click();+ res = await rec;+ check(res.status() === 201, `account without a GPU or key: saves its ${kind === "main" ? "clip" : kind}`);+ }+ check(marks.length >= 3 && marks.every((m) => m === "1"), `account without a GPU or key: every upload carries the Kinetic mark (${JSON.stringify(marks)})`);+ check(!(await bp.getByText(/Connect your GPU/).first().isVisible().catch(() => false)), "account without a GPU or key: no Connect card on save");+ await closeAll(bp);+ await bp.getByRole("button", { name: "Pick a clip" }).click();+ await bp.locator("[data-kinetic-sheet=clip]").waitFor();+ await bp.locator("[data-kinetic-upload-clip]").click();+ check(await bp.getByText(/Connect your GPU/).first().waitFor({ timeout: 10_000 }).then(() => true, () => false), "account without a GPU or key: Upload a clip opens the Connect card");+ await closeAll(bp);+ await bp.getByRole("button", { name: "Pick a clip" }).click();+ await bp.locator("[data-kinetic-clips] [data-kinetic-clip]").first().click();+ await bp.locator("[data-kinetic-clip-control] video").first().waitFor({ timeout: 60_000 });+ await bp.waitForTimeout(1200);+ rec = bp.waitForResponse((r) => r.url().endsWith("/api/generations/local") && r.request().method() === "POST", { timeout: 240_000 });+ await bp.locator("[data-kinetic-save=main]").click();+ res = await rec;+ const g = await res.json();+ check(res.status() === 201 && !!g.request?.params?.extra?.motion?.layers?.video, "account without a GPU or key: saves Big Number over its earlier Kinetic clip");+ await layout(bp, "account 1440", "editor with a clip");+ await bp.screenshot({ path: path.join(out, "bare-big-number-over-clip-1440.png") });+ await ctx.close();+ }+ check(pageErrors.length === 0, `no page errors (${JSON.stringify(pageErrors.slice(0, 5))})`);+} catch (e) {+ failures.push(`crashed: ${e?.stack ?? e}`);+ console.error(e);+} finally {+ await browser?.close().catch(() => {});+ await stopAll();+}++fs.writeFileSync(path.join(out, "e2e-result.json"), JSON.stringify({ failures, notes, timings }, null, 2));+console.log(failures.length ? `\n${failures.length} failed` : "\nall passed");+process.exit(failures.length ? 1 : 0);diff --git a/tests/e2e/kinetic-webkit.mjs b/tests/e2e/kinetic-webkit.mjsnew file mode 100644index 00000000..952a9ab1--- /dev/null+++ b/tests/e2e/kinetic-webkit.mjs@@ -0,0 +1,310 @@+// The Kinetic page in WebKit (Safari's engine), end to end. Needs a production build (`pnpm build`); starts `next start`+// on 3544 with a throwaway data folder, the owner's password and public sign-up on. Uses Playwright's WebKit and ffmpeg+// (a fixture clip). Everything it starts is stopped at the end.+//+// node tests/e2e/kinetic-webkit.mjs [evidence folder]+//+// KINETIC_WEBKIT_PORT moves the app.+//+// Guest (390 dark and 1440 light): the opening screen sends its title and tiles, the four examples draw, an example+// opens the editor and its preview plays, Pro's presets read Custom after a slider move, Save opens the sign-up card+// and nothing uploads; no sideways scroll, no page errors. Canvas filters: the grade's filter test agrees with what the+// canvas really draws. Owner: a frame saves as a PNG result of the export size; a clip saves where this WebKit has an+// encoder (otherwise the page says so and no result is made); a clip under the words either opens and saves a frame, or+// fails with its message within the time limit (never hangs, and the next save still works).+import { spawn, execFileSync, execSync } from "node:child_process";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { DESKTOP, loadPlaywright, PHONE, root } from "./_browser.mjs";++const PORT = Number(process.env.KINETIC_WEBKIT_PORT ?? 3544);+const APP = `http://127.0.0.1:${PORT}`;+const out = path.resolve(process.argv[2] ?? fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-kinetic-webkit-")));+fs.mkdirSync(out, { recursive: true });+const data = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-kinetic-webkit-data-"));+const PASSWORD = "owner password for kinetic in webkit";+const FFMPEG = process.env.FFMPEG ?? "ffmpeg";++const failures = [];+const notes = [];+const check = (ok, what) => {+ console.log(`${ok ? "ok " : "FAIL"} ${what}`);+ if (!ok) failures.push(what);+};+const note = (s) => {+ console.log(`note ${s}`);+ notes.push(s);+};+const wait = (ms) => new Promise((r) => setTimeout(r, ms));++const log = fs.openSync(path.join(out, "server.log"), "w");+const server = spawn(process.execPath, [path.join(root, "node_modules/next/dist/bin/next"), "start", "-p", String(PORT), "-H", "127.0.0.1"], {+ cwd: root,+ env: {+ ...process.env,+ NODE_ENV: "production",+ FUOBE_DATA_DIR: data,+ FUOBE_PASSWORD: PASSWORD,+ FUOBE_PUBLIC_SIGNUP: "1",+ FUOBE_DEMO_MODE: "on",+ COMFYUI_URL: "http://127.0.0.1:9",+ OLLAMA_URL: "http://127.0.0.1:9",+ LMSTUDIO_URL: "http://127.0.0.1:9",+ UNSLOTH_URL: "http://127.0.0.1:9",+ FUOBE_ACCOUNT_DISK_FREE_GB: "0.5",+ },+ stdio: ["ignore", log, log],+});+function stopAll() {+ try {+ if (process.platform === "win32") execSync(`taskkill /pid ${server.pid} /T /F`, { stdio: "ignore" });+ else server.kill("SIGTERM");+ } catch {}+}++const api = async (route, { method = "GET", body, cookie } = {}) => {+ const res = await fetch(APP + route, { method, headers: { Origin: APP, "Content-Type": "application/json", ...(cookie && { cookie }) }, ...(body !== undefined && { body: JSON.stringify(body) }) });+ const buf = Buffer.from(await res.arrayBuffer());+ let json = null;+ try {+ json = JSON.parse(buf.toString("utf8"));+ } catch {}+ return { status: res.status, json, buf, headers: res.headers };+};+const cookieOf = (res) => /fuobe_session=[^;]+/.exec(res.headers.get("set-cookie") ?? "")?.[0];+const pngSize = (buf) => (buf.subarray(1, 4).toString() === "PNG" ? { w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) } : null);+const MAIN = 'canvas[data-kinetic-player="main"]';+const pixels = (page) => page.evaluate((sel) => document.querySelector(sel)?.toDataURL() ?? "", MAIN);++async function closeAll(page) {+ for (let i = 0; i < 4 && (await page.locator('[role="dialog"]:visible, [role="alertdialog"]:visible, [data-kinetic-sheet=group]:visible').count()); i++) {+ await page.keyboard.press("Escape");+ await page.waitForTimeout(350);+ }+}+async function sideways(page, who) {+ const px = await page.evaluate(() => document.scrollingElement.scrollWidth - window.innerWidth);+ check(px <= 0, `${who}: no sideways scroll (${px} px)`);+}+/** The newest result of a feature, as the owner sees it. */+async function newest(cookie, feature) {+ const r = await api(`/api/generations?features=${feature}&limit=5`, { cookie });+ const list = Array.isArray(r.json) ? r.json : (r.json?.items ?? r.json?.generations ?? []);+ return list[0] ?? null;+}++let browser;+const pageErrors = [];+try {+ for (let i = 0; i < 180; i++) {+ try {+ const r = await fetch(`${APP}/login`);+ if (r.status < 500) break;+ } catch {}+ await wait(1000);+ }+ // The static page itself carries the opening screen (title and tiles) before any script runs.+ const html = await (await fetch(`${APP}/kinetic`)).text();+ check(/<h1[^>]*>Fuobe Kinetic Motion<\/h1>/.test(html), "the static page sends its title");+ check((html.match(/data-kinetic-scenes/g) ?? []).length > 0 && (html.match(/data-kinetic-tile=/g) ?? []).length >= 14, "the static page sends the example and scene tiles");++ const owner = cookieOf(await api("/api/auth/login", { method: "POST", body: { password: PASSWORD } }));+ check(!!owner, "owner signs in");+ const { webkit } = loadPlaywright();+ browser = await webkit.launch();+ note(`WebKit ${browser.version()}`);+ const withCookie = async (cookie, opts) => {+ const ctx = await browser.newContext({ ...opts, baseURL: APP });+ if (cookie) {+ const [n, v] = cookie.split("=");+ await ctx.addCookies([{ name: n, value: v, url: APP }]);+ }+ return ctx;+ };+ const watch = (page, who) => page.on("pageerror", (e) => pageErrors.push(`${who}: ${e.message}`));++ // ---- Guest: phone dark, desktop light.+ for (const [name, opts] of [+ ["390", { viewport: PHONE.viewport, hasTouch: true, colorScheme: "dark" }],+ ["1440", { ...DESKTOP, colorScheme: "light" }],+ ]) {+ const ctx = await withCookie(null, opts);+ const gp = await ctx.newPage();+ watch(gp, `guest ${name}`);+ let uploads = 0;+ gp.on("request", (r) => r.url().includes("/api/uploads") && uploads++);+ await gp.goto("/kinetic", { waitUntil: "load", timeout: 120_000 });+ await gp.locator("[data-kinetic-picker]:visible").first().waitFor({ timeout: 60_000 });+ check((await gp.locator("[data-kinetic-examples] [data-kinetic-tile]").count()) === 4, `guest ${name}: four examples`);+ check((await gp.locator("[data-kinetic-scenes] [data-kinetic-tile]").count()) === 10, `guest ${name}: all ten scenes`);+ // The examples are drawn by the engine (a canvas each, not blank).+ await gp.waitForFunction(() => document.querySelectorAll("[data-kinetic-examples] canvas").length === 4, null, { timeout: 60_000 }).catch(() => {});+ await gp.waitForTimeout(1500);+ const drawn = await gp.$$eval("[data-kinetic-examples] canvas", (cs) =>+ cs.map((c) => {+ try {+ const g = c.getContext("2d");+ const d = g.getImageData(0, 0, c.width, c.height).data;+ let lo = 255,+ hi = 0;+ for (let i = 0; i < d.length; i += 4 * 97) {+ const v = (d[i] + d[i + 1] + d[i + 2]) / 3;+ lo = Math.min(lo, v);+ hi = Math.max(hi, v);+ }+ return hi - lo;+ } catch {+ return -1;+ }+ }),+ );+ check(drawn.length === 4 && drawn.every((x) => x > 20), `guest ${name}: the four examples draw (${JSON.stringify(drawn)})`);+ await sideways(gp, `guest ${name} picker`);+ await gp.screenshot({ path: path.join(out, `webkit-guest-picker-${name}.png`), fullPage: true });+ await gp.locator("[data-kinetic-examples] [data-kinetic-tile=big-number]").click();+ await gp.locator(MAIN).waitFor({ timeout: 60_000 });+ await gp.waitForTimeout(1500);+ const a = await pixels(gp);+ await gp.waitForTimeout(500);+ check(a !== (await pixels(gp)), `guest ${name}: the example opens and its preview plays`);+ await sideways(gp, `guest ${name} editor`);+ await gp.getByRole("radio", { name: "Pro", exact: true }).click();+ await gp.getByRole("textbox", { name: "Pace value" }).fill("1.3");+ await gp.getByRole("textbox", { name: "Pace value" }).press("Enter");+ await gp.waitForTimeout(300);+ check(await gp.locator("[data-kinetic-presets=motion] [data-kinetic-custom]").isVisible(), `guest ${name}: a moved slider reads Custom`);+ await gp.screenshot({ path: path.join(out, `webkit-guest-editor-pro-${name}.png`) });+ await gp.locator("[data-kinetic-save=main]").click();+ check(await gp.getByText(/Create a free account/).first().waitFor({ timeout: 10_000 }).then(() => true, () => false), `guest ${name}: Save opens the sign-up card`);+ await closeAll(gp);+ check(uploads === 0, `guest ${name}: nothing uploads`);++ // Canvas filters: the page's test must match what a canvas really draws in this WebKit.+ const filters = await gp.evaluate(() => {+ const c = document.createElement("canvas");+ c.width = c.height = 1;+ const g = c.getContext("2d", { willReadFrequently: true });+ const s = document.createElement("canvas");+ s.width = s.height = 1;+ const sg = s.getContext("2d");+ sg.fillStyle = "rgb(200,40,40)";+ sg.fillRect(0, 0, 1, 1);+ const has = "filter" in Object.getPrototypeOf(g);+ g.filter = "saturate(0)";+ g.drawImage(s, 0, 0);+ const [r, gr, b] = g.getImageData(0, 0, 1, 1).data;+ return { has, grey: Math.abs(r - gr) < 12 && Math.abs(gr - b) < 12, px: [r, gr, b] };+ });+ note(`guest ${name}: canvas filter ${filters.has ? "present" : "missing"}, draws ${filters.grey ? "grey (works)" : `colour ${filters.px} (ignored)`}`);+ check(filters.has === filters.grey || !filters.has, `guest ${name}: the filter test reads what the canvas draws`);+ await ctx.close();+ }++ // ---- Owner (1440): a frame, a clip where an encoder exists, and a clip under the words.+ {+ const ctx = await withCookie(owner, { ...DESKTOP, colorScheme: "light" });+ const op = await ctx.newPage();+ watch(op, "owner");+ await op.goto("/kinetic?scene=big-number", { waitUntil: "load", timeout: 120_000 });+ await op.locator(MAIN).waitFor({ timeout: 60_000 });+ await op.waitForTimeout(1200);+ await op.getByRole("button", { name: "Export options" }).click();+ await op.locator("[data-kinetic-sheet=export]").waitFor();+ const mp4Line = await op.getByText(/can't make MP4 here/).count();+ note(`owner: MP4 ${mp4Line ? "not available in this WebKit" : "available"}`);+ await op.locator("[data-kinetic-save=frame]").click();+ const frameOk = await op.getByText(/Saved to your Library/).first().waitFor({ timeout: 60_000 }).then(() => true, () => false);+ check(frameOk, "owner: Save frame saves");+ const frame = await newest(owner, "kinetic-frame");+ if (frame) {+ const png = pngSize((await api(frame.outputs[0].url, { cookie: owner })).buf);+ check(png?.w === 1080 && png?.h === 1350, `owner: the frame is a 1080 × 1350 PNG (${JSON.stringify(png)})`);+ check(frame.outputs[0].width === 1080 && frame.outputs[0].height === 1350, "owner: the frame is recorded with its size");+ } else check(false, "owner: the frame is a result");+ await closeAll(op);++ // The clip: MP4, else WebM, else the page says so.+ await op.getByRole("button", { name: "Export options" }).click();+ await op.locator("[data-kinetic-sheet=export]").waitFor();+ if (mp4Line) await op.getByRole("radio", { name: "WebM", exact: true }).click();+ const save = op.locator("[data-kinetic-sheet=export] [data-kinetic-save=clip]");+ if (await save.isDisabled()) note("owner: no clip encoder in this WebKit (Save clip is off and says why)");+ else {+ const t0 = Date.now();+ await save.click();+ let clip = null;+ let err = 0;+ for (let i = 0; i < 180 && !clip && !err; i++) {+ await wait(1000);+ clip = await newest(owner, "kinetic");+ err = await op.getByText(/Couldn't save it|can't make/).count();+ }+ if (clip) {+ note(`owner: clip saved in ${Math.round((Date.now() - t0) / 100) / 10} s as ${clip?.outputs[0]?.contentType}`);+ check(!!clip && /^video\//.test(clip.outputs[0].contentType ?? ""), "owner: the clip is a video result");+ } else note(`owner: this WebKit could not encode the clip (${err ? "the page said so" : "no message"})`);+ }+ await closeAll(op);++ // A clip under the words: a 2 s H.264 fixture.+ const fixture = path.join(out, "fixture.mp4");+ execFileSync(FFMPEG, ["-y", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc2=size=640x360:rate=30:duration=2", "-pix_fmt", "yuv420p", "-c:v", "libx264", fixture]);+ const fd = new FormData();+ fd.append("file", new Blob([fs.readFileSync(fixture)], { type: "video/mp4" }), "fixture.mp4");+ const up = await (await fetch(APP + "/api/uploads", { method: "POST", headers: { Origin: APP, cookie: owner }, body: fd })).json();+ check(typeof up?.url === "string", "owner: the fixture clip uploads");+ const opened = await op.evaluate(async (url) => {+ const el = document.createElement("video");+ el.muted = true;+ el.playsInline = true;+ el.src = url;+ el.load();+ const t0 = performance.now();+ const r = await new Promise((res) => {+ el.addEventListener("loadeddata", () => res("loaded"), { once: true });+ el.addEventListener("error", () => res("error"), { once: true });+ setTimeout(() => res("timeout"), 16_000);+ });+ return { r, ms: Math.round(performance.now() - t0) };+ }, up.url);+ note(`owner: this WebKit opens an H.264 clip: ${opened.r} after ${opened.ms} ms`);+ // Pick it through the address of a saved result is not possible here, so set it in the browser draft and reopen.+ await op.goto("/kinetic?scene=big-number", { waitUntil: "load" });+ await op.locator(MAIN).waitFor({ timeout: 60_000 });+ const clipButton = op.getByRole("button", { name: /Pick a clip|Add a clip|Choose a clip/ }).first();+ if (await clipButton.count()) {+ await clipButton.click();+ await op.locator("[data-kinetic-sheet=clip]").waitFor();+ await op.locator("[data-kinetic-clips] [data-kinetic-clip]").first().click();+ await op.waitForTimeout(500);+ await op.getByRole("button", { name: "Export options" }).click();+ await op.locator("[data-kinetic-sheet=export]").waitFor();+ const t0 = Date.now();+ await op.locator("[data-kinetic-save=frame]").click();+ const done = await Promise.race([+ op.getByText(/Saved to your Library|Already saved/).first().waitFor({ timeout: 45_000 }).then(() => "saved", () => null),+ op.getByText(/We can't open that clip|We can't read that clip/).first().waitFor({ timeout: 45_000 }).then(() => "message", () => null),+ ]);+ const secs = Math.round((Date.now() - t0) / 100) / 10;+ check(done === "saved" || done === "message", `owner: a frame over the clip either saves or says why, never hangs (${done ?? "nothing"} after ${secs} s)`);+ // The next save still works (a failed clip never blocks the jobs).+ await op.waitForTimeout(500);+ const busy = await op.locator("[data-kinetic-save=frame]").isDisabled();+ check(!busy, "owner: Save frame is ready again afterwards");+ await op.screenshot({ path: path.join(out, "webkit-owner-clip.png") });+ } else note("owner: no clip control found on Big Number");+ await sideways(op, "owner 1440 editor");+ await ctx.close();+ }++ check(pageErrors.length === 0, `no page errors (${JSON.stringify(pageErrors.slice(0, 5))})`);+} catch (e) {+ check(false, `the run finished (${e.message})`);+} finally {+ await browser?.close().catch(() => {});+ stopAll();+ fs.writeFileSync(path.join(out, "webkit-result.json"), JSON.stringify({ failures, notes }, null, 2));+ console.log(failures.length ? `\n${failures.length} FAILED` : "\nALL PASSED");+ process.exitCode = failures.length ? 1 : 0;+}diff --git a/tests/e2e/no-horizontal-scroll.mjs b/tests/e2e/no-horizontal-scroll.mjsindex 22fc5a18..bb3c6d1a 100644--- a/tests/e2e/no-horizontal-scroll.mjs+++ b/tests/e2e/no-horizontal-scroll.mjs@@ -32,7 +32,8 @@ async function discoverRoutes() {const chats = [askFirst?.id, autoRun?.id].filter(Boolean).map((id) => `/assist?c=${id}`);// A skill with a recipe: its Run form opens from /assist/skills?run=<name>.const recipeSkill = await recipeSkillSample();- const samples = [...urls, ...chats, ...querySamples({ recipeSkill }), "/library?tab=favorites", "/login", "/this-page-does-not-exist"];+ // Kinetic opens on a scene by its address (the editor), as well as on its scene picker (/kinetic).+ const samples = [...urls, ...chats, ...querySamples({ recipeSkill }), "/library?tab=favorites", "/kinetic?scene=big-number", "/login", "/this-page-does-not-exist"];if (!recipeSkill) console.log("note: couldn't create a sample skill with a recipe, only an unknown /assist/skills?run= is checked");if (!project?.id) console.log("note: couldn't create a sample cinema project, only an unknown /cinema/[id] is checked");if (!canvas?.id) console.log("note: couldn't create a sample canvas, only an unknown /canvas/[id] is checked");diff --git a/tests/fixtures/motion-identity.json b/tests/fixtures/motion-identity.jsonnew file mode 100644index 00000000..7e0d0238--- /dev/null+++ b/tests/fixtures/motion-identity.json@@ -0,0 +1 @@+{"m2-line-reveal|marketing/line-reveal|9:16|pace=calm,look=light,line=fine":"f3ffd5e19dbba715","m2-line-reveal|marketing/line-reveal|9:16|pace=calm,look=light,line=bold":"18972986f75f1c8e","m2-line-reveal|marketing/line-reveal|9:16|pace=calm,look=dark,line=fine":"c716c09ff6dfbc47","m2-line-reveal|marketing/line-reveal|9:16|pace=calm,look=dark,line=bold":"e6b8b09a392356ff","m2-line-reveal|marketing/line-reveal|9:16|pace=calm,look=brand,line=fine":"336a9a294e884e21","m2-line-reveal|marketing/line-reveal|9:16|pace=calm,look=brand,line=bold":"df34cbb1ef9d6ac3","m2-line-reveal|marketing/line-reveal|9:16|pace=punchy,look=light,line=fine":"ea4940a0f8161784","m2-line-reveal|marketing/line-reveal|9:16|pace=punchy,look=light,line=bold":"63ed33456c23c450","m2-line-reveal|marketing/line-reveal|9:16|pace=punchy,look=dark,line=fine":"f42f0f448de74469","m2-line-reveal|marketing/line-reveal|9:16|pace=punchy,look=dark,line=bold":"739c6b05b5da78cc","m2-line-reveal|marketing/line-reveal|9:16|pace=punchy,look=brand,line=fine":"66721b6ce7461769","m2-line-reveal|marketing/line-reveal|9:16|pace=punchy,look=brand,line=bold":"11d4c98a2920e7c9","m2-line-reveal|marketing/line-reveal|1:1|pace=calm,look=light,line=fine":"157bcceaef374f3c","m2-line-reveal|marketing/line-reveal|1:1|pace=calm,look=light,line=bold":"e60f275c81b0ddae","m2-line-reveal|marketing/line-reveal|1:1|pace=calm,look=dark,line=fine":"2d25495e208a060a","m2-line-reveal|marketing/line-reveal|1:1|pace=calm,look=dark,line=bold":"c9c76b31f7c7d7ae","m2-line-reveal|marketing/line-reveal|1:1|pace=calm,look=brand,line=fine":"dffa08b5f22c0cae","m2-line-reveal|marketing/line-reveal|1:1|pace=calm,look=brand,line=bold":"0e0ec551870c360b","m2-line-reveal|marketing/line-reveal|1:1|pace=punchy,look=light,line=fine":"b46707162812e997","m2-line-reveal|marketing/line-reveal|1:1|pace=punchy,look=light,line=bold":"da05127a3abb2f17","m2-line-reveal|marketing/line-reveal|1:1|pace=punchy,look=dark,line=fine":"a14f86f600e42446","m2-line-reveal|marketing/line-reveal|1:1|pace=punchy,look=dark,line=bold":"b66d01cf099b8f59","m2-line-reveal|marketing/line-reveal|1:1|pace=punchy,look=brand,line=fine":"edd1409c2d7f564f","m2-line-reveal|marketing/line-reveal|1:1|pace=punchy,look=brand,line=bold":"e966564b59f2f930","m2-line-reveal|marketing/line-reveal|16:9|pace=calm,look=light,line=fine":"90adbb7add49af0d","m2-line-reveal|marketing/line-reveal|16:9|pace=calm,look=light,line=bold":"ca97b4d1b690d079","m2-line-reveal|marketing/line-reveal|16:9|pace=calm,look=dark,line=fine":"8c27e16bf54b96de","m2-line-reveal|marketing/line-reveal|16:9|pace=calm,look=dark,line=bold":"b8cbed3fd2a4d8bc","m2-line-reveal|marketing/line-reveal|16:9|pace=calm,look=brand,line=fine":"b3b7e3c8fb401e2c","m2-line-reveal|marketing/line-reveal|16:9|pace=calm,look=brand,line=bold":"5f73d78952ca95d8","m2-line-reveal|marketing/line-reveal|16:9|pace=punchy,look=light,line=fine":"275e0d64b764dd93","m2-line-reveal|marketing/line-reveal|16:9|pace=punchy,look=light,line=bold":"54ef589a921b95f3","m2-line-reveal|marketing/line-reveal|16:9|pace=punchy,look=dark,line=fine":"113d4ec863204fcd","m2-line-reveal|marketing/line-reveal|16:9|pace=punchy,look=dark,line=bold":"c7d31e2b1d7be727","m2-line-reveal|marketing/line-reveal|16:9|pace=punchy,look=brand,line=fine":"677f42b439ecfab3","m2-line-reveal|marketing/line-reveal|16:9|pace=punchy,look=brand,line=bold":"f2ba5b32cfa5e403","m2-line-reveal|marketing/line-reveal|4:5|pace=calm,look=light,line=fine":"3e87e4e2aa1311c5","m2-line-reveal|marketing/line-reveal|4:5|pace=calm,look=light,line=bold":"59be374a99807c33","m2-line-reveal|marketing/line-reveal|4:5|pace=calm,look=dark,line=fine":"50764bfd6ade4f43","m2-line-reveal|marketing/line-reveal|4:5|pace=calm,look=dark,line=bold":"023eecf677e7d5e2","m2-line-reveal|marketing/line-reveal|4:5|pace=calm,look=brand,line=fine":"6e8e2392c68092b6","m2-line-reveal|marketing/line-reveal|4:5|pace=calm,look=brand,line=bold":"fc3b429c3252ccd0","m2-line-reveal|marketing/line-reveal|4:5|pace=punchy,look=light,line=fine":"4e54e756e4bbedb8","m2-line-reveal|marketing/line-reveal|4:5|pace=punchy,look=light,line=bold":"2fff48ed6eaadc1c","m2-line-reveal|marketing/line-reveal|4:5|pace=punchy,look=dark,line=fine":"9ce5d5b4e4ed845a","m2-line-reveal|marketing/line-reveal|4:5|pace=punchy,look=dark,line=bold":"b1c9119356fb6577","m2-line-reveal|marketing/line-reveal|4:5|pace=punchy,look=brand,line=fine":"feb77865414df64e","m2-line-reveal|marketing/line-reveal|4:5|pace=punchy,look=brand,line=bold":"c435378107d85109","m2-retro-starburst|marketing/starburst|9:16|pace=calm,look=light":"c846649b9f4cc810","m2-retro-starburst|marketing/starburst|9:16|pace=calm,look=dark":"6f72cc19a32ef05d","m2-retro-starburst|marketing/starburst|9:16|pace=calm,look=brand":"66c42972dd0f6f27","m2-retro-starburst|marketing/starburst|9:16|pace=punchy,look=light":"6d3a0e8463a077e9","m2-retro-starburst|marketing/starburst|9:16|pace=punchy,look=dark":"8a841fef617dbb10","m2-retro-starburst|marketing/starburst|9:16|pace=punchy,look=brand":"d4ca7976db0ba04d","m2-retro-starburst|marketing/starburst|1:1|pace=calm,look=light":"2eceb7e76e2b8e81","m2-retro-starburst|marketing/starburst|1:1|pace=calm,look=dark":"41367b52eed6b5f7","m2-retro-starburst|marketing/starburst|1:1|pace=calm,look=brand":"e2a5751c6f8ce3ef","m2-retro-starburst|marketing/starburst|1:1|pace=punchy,look=light":"856758bccafc4948","m2-retro-starburst|marketing/starburst|1:1|pace=punchy,look=dark":"b630ac7fff58a36e","m2-retro-starburst|marketing/starburst|1:1|pace=punchy,look=brand":"f47e6d317e29e95a","m2-retro-starburst|marketing/starburst|16:9|pace=calm,look=light":"8cd707085fccd613","m2-retro-starburst|marketing/starburst|16:9|pace=calm,look=dark":"bc653b10104626d2","m2-retro-starburst|marketing/starburst|16:9|pace=calm,look=brand":"7bbf8b933aa6fc5a","m2-retro-starburst|marketing/starburst|16:9|pace=punchy,look=light":"298dcf54e135b208","m2-retro-starburst|marketing/starburst|16:9|pace=punchy,look=dark":"e21635c24d56868c","m2-retro-starburst|marketing/starburst|16:9|pace=punchy,look=brand":"0ebedcb9d51007e6","m2-retro-starburst|marketing/starburst|4:5|pace=calm,look=light":"e7bdabdc45519f5a","m2-retro-starburst|marketing/starburst|4:5|pace=calm,look=dark":"65b7681ddc5eaa23","m2-retro-starburst|marketing/starburst|4:5|pace=calm,look=brand":"f4730d867b4be945","m2-retro-starburst|marketing/starburst|4:5|pace=punchy,look=light":"b043df406dec8c4b","m2-retro-starburst|marketing/starburst|4:5|pace=punchy,look=dark":"daa53e5f5c5ab368","m2-retro-starburst|marketing/starburst|4:5|pace=punchy,look=brand":"74aafe1ee8a6644a","m2-offer-badge|marketing/offer-badge|9:16|pace=calm,look=light":"e5cba7ef9c066bbf","m2-offer-badge|marketing/offer-badge|9:16|pace=calm,look=dark":"5d2ae2c2141a240e","m2-offer-badge|marketing/offer-badge|9:16|pace=calm,look=brand":"3fce96031cd5fb5d","m2-offer-badge|marketing/offer-badge|9:16|pace=punchy,look=light":"6e6e75d81d9e718c","m2-offer-badge|marketing/offer-badge|9:16|pace=punchy,look=dark":"642ba35be34b29c2","m2-offer-badge|marketing/offer-badge|9:16|pace=punchy,look=brand":"fdd332df8585319d","m2-offer-badge|marketing/offer-badge|1:1|pace=calm,look=light":"ce6d0ff5b09dcbac","m2-offer-badge|marketing/offer-badge|1:1|pace=calm,look=dark":"fbc8809fb387dc3f","m2-offer-badge|marketing/offer-badge|1:1|pace=calm,look=brand":"1df38c000d1c9bb7","m2-offer-badge|marketing/offer-badge|1:1|pace=punchy,look=light":"f720c06e98b7d75c","m2-offer-badge|marketing/offer-badge|1:1|pace=punchy,look=dark":"5c4c1f847230531e","m2-offer-badge|marketing/offer-badge|1:1|pace=punchy,look=brand":"3161a69233819090","m2-offer-badge|marketing/offer-badge|16:9|pace=calm,look=light":"10febc08f883b5e7","m2-offer-badge|marketing/offer-badge|16:9|pace=calm,look=dark":"4ad1697daa7357e8","m2-offer-badge|marketing/offer-badge|16:9|pace=calm,look=brand":"996c2256d8a933ff","m2-offer-badge|marketing/offer-badge|16:9|pace=punchy,look=light":"84d024ddd98ab50c","m2-offer-badge|marketing/offer-badge|16:9|pace=punchy,look=dark":"8db3f8a5730d8209","m2-offer-badge|marketing/offer-badge|16:9|pace=punchy,look=brand":"7fd41115114f83b1","m2-offer-badge|marketing/offer-badge|4:5|pace=calm,look=light":"aed6e7a9a0412beb","m2-offer-badge|marketing/offer-badge|4:5|pace=calm,look=dark":"4fdd5a913696acc1","m2-offer-badge|marketing/offer-badge|4:5|pace=calm,look=brand":"0efeca49a2480736","m2-offer-badge|marketing/offer-badge|4:5|pace=punchy,look=light":"03d91a0e070919e0","m2-offer-badge|marketing/offer-badge|4:5|pace=punchy,look=dark":"4ecaec97bf74cbcb","m2-offer-badge|marketing/offer-badge|4:5|pace=punchy,look=brand":"d94baaabc3b2609e","ms-feature-cards|marketing/feature-cards|9:16|pace=calm,look=light":"43077707a6bd8829","ms-feature-cards|marketing/feature-cards|9:16|pace=calm,look=dark":"8d2d649303a43dd9","ms-feature-cards|marketing/feature-cards|9:16|pace=calm,look=brand":"ce7962ee86007056","ms-feature-cards|marketing/feature-cards|9:16|pace=punchy,look=light":"c5b757f6638df9fe","ms-feature-cards|marketing/feature-cards|9:16|pace=punchy,look=dark":"2da795c2cbf28165","ms-feature-cards|marketing/feature-cards|9:16|pace=punchy,look=brand":"914d4dd330e6c689","ms-feature-cards|marketing/feature-cards|1:1|pace=calm,look=light":"0f5981cbed30698d","ms-feature-cards|marketing/feature-cards|1:1|pace=calm,look=dark":"1d40cea633f6811f","ms-feature-cards|marketing/feature-cards|1:1|pace=calm,look=brand":"449fecc7b4611605","ms-feature-cards|marketing/feature-cards|1:1|pace=punchy,look=light":"4df6414bd8ea5e27","ms-feature-cards|marketing/feature-cards|1:1|pace=punchy,look=dark":"e3c642d0668ad0d8","ms-feature-cards|marketing/feature-cards|1:1|pace=punchy,look=brand":"24be7873832b2cd7","ms-feature-cards|marketing/feature-cards|16:9|pace=calm,look=light":"fa66cc3a7f4b30be","ms-feature-cards|marketing/feature-cards|16:9|pace=calm,look=dark":"946325a84454f327","ms-feature-cards|marketing/feature-cards|16:9|pace=calm,look=brand":"7ecbe98d2d548644","ms-feature-cards|marketing/feature-cards|16:9|pace=punchy,look=light":"8a05e495a7bfd4e9","ms-feature-cards|marketing/feature-cards|16:9|pace=punchy,look=dark":"acd0d878c121e534","ms-feature-cards|marketing/feature-cards|16:9|pace=punchy,look=brand":"7f46874eaec05f3b","ms-feature-cards|marketing/feature-cards|4:5|pace=calm,look=light":"fb27f75bfb096978","ms-feature-cards|marketing/feature-cards|4:5|pace=calm,look=dark":"f544ce9bfcd40636","ms-feature-cards|marketing/feature-cards|4:5|pace=calm,look=brand":"05c4e6c0470103a6","ms-feature-cards|marketing/feature-cards|4:5|pace=punchy,look=light":"618417fde045251c","ms-feature-cards|marketing/feature-cards|4:5|pace=punchy,look=dark":"c9ae14b0baf48f8c","ms-feature-cards|marketing/feature-cards|4:5|pace=punchy,look=brand":"be8b74a7e0fc499f","ms-kinetic-headline|marketing/kinetic-headline|9:16|pace=calm,look=light,align=centre":"de0161a124680dc4","ms-kinetic-headline|marketing/kinetic-headline|9:16|pace=calm,look=light,align=left":"a2bc0861c455e044","ms-kinetic-headline|marketing/kinetic-headline|9:16|pace=calm,look=dark,align=centre":"c6cb94599f032c0a","ms-kinetic-headline|marketing/kinetic-headline|9:16|pace=calm,look=dark,align=left":"6121928f5253b238","ms-kinetic-headline|marketing/kinetic-headline|9:16|pace=calm,look=brand,align=centre":"bbaba0d06c968f2c","ms-kinetic-headline|marketing/kinetic-headline|9:16|pace=calm,look=brand,align=left":"849f3d1d0fe7943f","ms-kinetic-headline|marketing/kinetic-headline|9:16|pace=punchy,look=light,align=centre":"d7bcfc4105d898d0","ms-kinetic-headline|marketing/kinetic-headline|9:16|pace=punchy,look=light,align=left":"1bdf1bc15ce30b04","ms-kinetic-headline|marketing/kinetic-headline|9:16|pace=punchy,look=dark,align=centre":"96df3f18142b30f3","ms-kinetic-headline|marketing/kinetic-headline|9:16|pace=punchy,look=dark,align=left":"e969dc4cc2d51e70","ms-kinetic-headline|marketing/kinetic-headline|9:16|pace=punchy,look=brand,align=centre":"c573ba6b66f1aee4","ms-kinetic-headline|marketing/kinetic-headline|9:16|pace=punchy,look=brand,align=left":"cf4548b746d5517a","ms-kinetic-headline|marketing/kinetic-headline|1:1|pace=calm,look=light,align=centre":"d873cad0feb54f48","ms-kinetic-headline|marketing/kinetic-headline|1:1|pace=calm,look=light,align=left":"2546335aa466bafc","ms-kinetic-headline|marketing/kinetic-headline|1:1|pace=calm,look=dark,align=centre":"2f397eb1940d61de","ms-kinetic-headline|marketing/kinetic-headline|1:1|pace=calm,look=dark,align=left":"f757919294101fbb","ms-kinetic-headline|marketing/kinetic-headline|1:1|pace=calm,look=brand,align=centre":"98bc496745ff51db","ms-kinetic-headline|marketing/kinetic-headline|1:1|pace=calm,look=brand,align=left":"0f5e2df4f2401258","ms-kinetic-headline|marketing/kinetic-headline|1:1|pace=punchy,look=light,align=centre":"70f93becf5c16429","ms-kinetic-headline|marketing/kinetic-headline|1:1|pace=punchy,look=light,align=left":"b161c06da9d450f4","ms-kinetic-headline|marketing/kinetic-headline|1:1|pace=punchy,look=dark,align=centre":"6d8e7498ffd2ddc1","ms-kinetic-headline|marketing/kinetic-headline|1:1|pace=punchy,look=dark,align=left":"d5f490fca0d88389","ms-kinetic-headline|marketing/kinetic-headline|1:1|pace=punchy,look=brand,align=centre":"9023949c549b1830","ms-kinetic-headline|marketing/kinetic-headline|1:1|pace=punchy,look=brand,align=left":"22cd997181e1a587","ms-kinetic-headline|marketing/kinetic-headline|16:9|pace=calm,look=light,align=centre":"f901875b5de0a914","ms-kinetic-headline|marketing/kinetic-headline|16:9|pace=calm,look=light,align=left":"313bb1ee2ae63716","ms-kinetic-headline|marketing/kinetic-headline|16:9|pace=calm,look=dark,align=centre":"81d33c087d147044","ms-kinetic-headline|marketing/kinetic-headline|16:9|pace=calm,look=dark,align=left":"85fb0e14d456ecab","ms-kinetic-headline|marketing/kinetic-headline|16:9|pace=calm,look=brand,align=centre":"7088a22218fe5b3f","ms-kinetic-headline|marketing/kinetic-headline|16:9|pace=calm,look=brand,align=left":"d873b8e2b0850447","ms-kinetic-headline|marketing/kinetic-headline|16:9|pace=punchy,look=light,align=centre":"423706a61445d598","ms-kinetic-headline|marketing/kinetic-headline|16:9|pace=punchy,look=light,align=left":"6246d502247d095b","ms-kinetic-headline|marketing/kinetic-headline|16:9|pace=punchy,look=dark,align=centre":"78cf533246c1947d","ms-kinetic-headline|marketing/kinetic-headline|16:9|pace=punchy,look=dark,align=left":"455f1a9abcaca03e","ms-kinetic-headline|marketing/kinetic-headline|16:9|pace=punchy,look=brand,align=centre":"a5bb433d19d9978b","ms-kinetic-headline|marketing/kinetic-headline|16:9|pace=punchy,look=brand,align=left":"338a4ede4b4d51db","ms-kinetic-headline|marketing/kinetic-headline|4:5|pace=calm,look=light,align=centre":"6019829067c75073","ms-kinetic-headline|marketing/kinetic-headline|4:5|pace=calm,look=light,align=left":"f9c1c1e791249c10","ms-kinetic-headline|marketing/kinetic-headline|4:5|pace=calm,look=dark,align=centre":"fbc9863b0f46c6f6","ms-kinetic-headline|marketing/kinetic-headline|4:5|pace=calm,look=dark,align=left":"10ae17a651758d43","ms-kinetic-headline|marketing/kinetic-headline|4:5|pace=calm,look=brand,align=centre":"7353f355550e0d1a","ms-kinetic-headline|marketing/kinetic-headline|4:5|pace=calm,look=brand,align=left":"2fe3216a3a6ca2d0","ms-kinetic-headline|marketing/kinetic-headline|4:5|pace=punchy,look=light,align=centre":"6cf0d2e43036f7d0","ms-kinetic-headline|marketing/kinetic-headline|4:5|pace=punchy,look=light,align=left":"de49b764aed15d40","ms-kinetic-headline|marketing/kinetic-headline|4:5|pace=punchy,look=dark,align=centre":"ce8713d7d9812b62","ms-kinetic-headline|marketing/kinetic-headline|4:5|pace=punchy,look=dark,align=left":"d4ee0d257bab464a","ms-kinetic-headline|marketing/kinetic-headline|4:5|pace=punchy,look=brand,align=centre":"e3761093216eae41","ms-kinetic-headline|marketing/kinetic-headline|4:5|pace=punchy,look=brand,align=left":"96c53c45aa296109","ms-dashboard-zoom|marketing/stat-dashboard|9:16|pace=calm,look=light":"db4ec74507635b0f","ms-dashboard-zoom|marketing/stat-dashboard|9:16|pace=calm,look=dark":"d6315404e7436d4a","ms-dashboard-zoom|marketing/stat-dashboard|9:16|pace=calm,look=brand":"b078674cbf1238c5","ms-dashboard-zoom|marketing/stat-dashboard|9:16|pace=punchy,look=light":"e22424e3182747ee","ms-dashboard-zoom|marketing/stat-dashboard|9:16|pace=punchy,look=dark":"9708ff262232cb0b","ms-dashboard-zoom|marketing/stat-dashboard|9:16|pace=punchy,look=brand":"7f073c185b8d04b2","ms-dashboard-zoom|marketing/stat-dashboard|1:1|pace=calm,look=light":"1fc19ba143366464","ms-dashboard-zoom|marketing/stat-dashboard|1:1|pace=calm,look=dark":"f18f649f650d1a14","ms-dashboard-zoom|marketing/stat-dashboard|1:1|pace=calm,look=brand":"311a7f996a39856f","ms-dashboard-zoom|marketing/stat-dashboard|1:1|pace=punchy,look=light":"6465f8e48872f162","ms-dashboard-zoom|marketing/stat-dashboard|1:1|pace=punchy,look=dark":"bd6e81db295b0089","ms-dashboard-zoom|marketing/stat-dashboard|1:1|pace=punchy,look=brand":"80c9a1c2bf903db4","ms-dashboard-zoom|marketing/stat-dashboard|16:9|pace=calm,look=light":"f9ddc6e254b5ba30","ms-dashboard-zoom|marketing/stat-dashboard|16:9|pace=calm,look=dark":"9e6ca782e71ed26d","ms-dashboard-zoom|marketing/stat-dashboard|16:9|pace=calm,look=brand":"fa3873bfbdd2d843","ms-dashboard-zoom|marketing/stat-dashboard|16:9|pace=punchy,look=light":"a9a24b4b4bc0c20c","ms-dashboard-zoom|marketing/stat-dashboard|16:9|pace=punchy,look=dark":"19cbd449596154d7","ms-dashboard-zoom|marketing/stat-dashboard|16:9|pace=punchy,look=brand":"4bdb05177745e176","ms-dashboard-zoom|marketing/stat-dashboard|4:5|pace=calm,look=light":"3c963ad530e7ffae","ms-dashboard-zoom|marketing/stat-dashboard|4:5|pace=calm,look=dark":"76c56967a43aa0bc","ms-dashboard-zoom|marketing/stat-dashboard|4:5|pace=calm,look=brand":"fc88c777370c3c5d","ms-dashboard-zoom|marketing/stat-dashboard|4:5|pace=punchy,look=light":"f5b8af07cdc17be7","ms-dashboard-zoom|marketing/stat-dashboard|4:5|pace=punchy,look=dark":"d0cdba0a1ca29a97","ms-dashboard-zoom|marketing/stat-dashboard|4:5|pace=punchy,look=brand":"2dfc1b86890b4635","ms-logo-sting|marketing/logo-sting|9:16|pace=calm,look=light":"4e40c978c3c3f6db","ms-logo-sting|marketing/logo-sting|9:16|pace=calm,look=dark":"18e85ae847720d80","ms-logo-sting|marketing/logo-sting|9:16|pace=calm,look=brand":"446268a0399d0a74","ms-logo-sting|marketing/logo-sting|9:16|pace=punchy,look=light":"5ae5f0a5b3ccd893","ms-logo-sting|marketing/logo-sting|9:16|pace=punchy,look=dark":"57648485f1bc437d","ms-logo-sting|marketing/logo-sting|9:16|pace=punchy,look=brand":"8048ba4dbc422075","ms-logo-sting|marketing/logo-sting|1:1|pace=calm,look=light":"4e9d2e08bde3bbb3","ms-logo-sting|marketing/logo-sting|1:1|pace=calm,look=dark":"8bfda8ef8f6e6633","ms-logo-sting|marketing/logo-sting|1:1|pace=calm,look=brand":"3f4a09ea682a77f5","ms-logo-sting|marketing/logo-sting|1:1|pace=punchy,look=light":"63c5b7d3843021d3","ms-logo-sting|marketing/logo-sting|1:1|pace=punchy,look=dark":"99853de16ad4ec1f","ms-logo-sting|marketing/logo-sting|1:1|pace=punchy,look=brand":"a4ab497a952f8317","ms-logo-sting|marketing/logo-sting|16:9|pace=calm,look=light":"f6e8b24bfd17ede4","ms-logo-sting|marketing/logo-sting|16:9|pace=calm,look=dark":"58c751235f7c969b","ms-logo-sting|marketing/logo-sting|16:9|pace=calm,look=brand":"dbbf680ebdcc9d69","ms-logo-sting|marketing/logo-sting|16:9|pace=punchy,look=light":"9da15aedaca5352b","ms-logo-sting|marketing/logo-sting|16:9|pace=punchy,look=dark":"f5a5ac8dd674fddd","ms-logo-sting|marketing/logo-sting|16:9|pace=punchy,look=brand":"7123ab15c098ed47","ms-logo-sting|marketing/logo-sting|4:5|pace=calm,look=light":"15f9475d06f38c5a","ms-logo-sting|marketing/logo-sting|4:5|pace=calm,look=dark":"956b35de3e717423","ms-logo-sting|marketing/logo-sting|4:5|pace=calm,look=brand":"1b9ed22627f11b0c","ms-logo-sting|marketing/logo-sting|4:5|pace=punchy,look=light":"b9effea4316450b2","ms-logo-sting|marketing/logo-sting|4:5|pace=punchy,look=dark":"06f9c79ea66060f1","ms-logo-sting|marketing/logo-sting|4:5|pace=punchy,look=brand":"cf96cee9bc6f8cbd","ms-big-number|marketing/big-number|9:16|pace=calm,look=light":"1967186945ae8817","ms-big-number|marketing/big-number|9:16|pace=calm,look=dark":"d1b0e5945dfd8ace","ms-big-number|marketing/big-number|9:16|pace=calm,look=brand":"a76d29023362665b","ms-big-number|marketing/big-number|9:16|pace=punchy,look=light":"67d89eec6276cc28","ms-big-number|marketing/big-number|9:16|pace=punchy,look=dark":"26fdf8d7800672fd","ms-big-number|marketing/big-number|9:16|pace=punchy,look=brand":"41f5adac0289c31b","ms-big-number|marketing/big-number|1:1|pace=calm,look=light":"be46fc3ab1dd98b8","ms-big-number|marketing/big-number|1:1|pace=calm,look=dark":"d408575bf62da611","ms-big-number|marketing/big-number|1:1|pace=calm,look=brand":"b5a179c9484471b6","ms-big-number|marketing/big-number|1:1|pace=punchy,look=light":"a4e01102f7fb3e81","ms-big-number|marketing/big-number|1:1|pace=punchy,look=dark":"40fc5136032886f3","ms-big-number|marketing/big-number|1:1|pace=punchy,look=brand":"ca4fb48004963396","ms-big-number|marketing/big-number|16:9|pace=calm,look=light":"db1dcb57d66b2061","ms-big-number|marketing/big-number|16:9|pace=calm,look=dark":"2f1f7cccbedf9a12","ms-big-number|marketing/big-number|16:9|pace=calm,look=brand":"f16ef815bb6dd408","ms-big-number|marketing/big-number|16:9|pace=punchy,look=light":"57ef1505e40de22c","ms-big-number|marketing/big-number|16:9|pace=punchy,look=dark":"739818c9fd4a4415","ms-big-number|marketing/big-number|16:9|pace=punchy,look=brand":"803dff7b1cd1a1b3","ms-big-number|marketing/big-number|4:5|pace=calm,look=light":"59c19e4d05b9becd","ms-big-number|marketing/big-number|4:5|pace=calm,look=dark":"bae5c0893389afce","ms-big-number|marketing/big-number|4:5|pace=calm,look=brand":"e9cad349059a9ee2","ms-big-number|marketing/big-number|4:5|pace=punchy,look=light":"5efc901aefdbf978","ms-big-number|marketing/big-number|4:5|pace=punchy,look=dark":"6990c071369b1848","ms-big-number|marketing/big-number|4:5|pace=punchy,look=brand":"661ca9bea77ff5f8","ms-five-star-quote|marketing/quote|9:16|pace=calm,look=light":"9550e4fb9b23a096","ms-five-star-quote|marketing/quote|9:16|pace=calm,look=dark":"49c2f3ec98691468","ms-five-star-quote|marketing/quote|9:16|pace=calm,look=brand":"54116e1a0ea972f1","ms-five-star-quote|marketing/quote|9:16|pace=punchy,look=light":"d8fd199877664589","ms-five-star-quote|marketing/quote|9:16|pace=punchy,look=dark":"4dae935c4496c561","ms-five-star-quote|marketing/quote|9:16|pace=punchy,look=brand":"d657aa28da5b7060","ms-five-star-quote|marketing/quote|1:1|pace=calm,look=light":"ceb8b534e2b92a24","ms-five-star-quote|marketing/quote|1:1|pace=calm,look=dark":"21013adb089f0428","ms-five-star-quote|marketing/quote|1:1|pace=calm,look=brand":"f014f80367ead763","ms-five-star-quote|marketing/quote|1:1|pace=punchy,look=light":"7b2389777046724b","ms-five-star-quote|marketing/quote|1:1|pace=punchy,look=dark":"f906c2dc9090539e","ms-five-star-quote|marketing/quote|1:1|pace=punchy,look=brand":"468a29431a8c9653","ms-five-star-quote|marketing/quote|16:9|pace=calm,look=light":"57edb1c8e2bf9cda","ms-five-star-quote|marketing/quote|16:9|pace=calm,look=dark":"aa924c258d6bcd6a","ms-five-star-quote|marketing/quote|16:9|pace=calm,look=brand":"c603c9e0ef797555","ms-five-star-quote|marketing/quote|16:9|pace=punchy,look=light":"1d29bc9e557a2678","ms-five-star-quote|marketing/quote|16:9|pace=punchy,look=dark":"d1adaacdae834735","ms-five-star-quote|marketing/quote|16:9|pace=punchy,look=brand":"ed45e80ab2d15b80","ms-five-star-quote|marketing/quote|4:5|pace=calm,look=light":"38b2565dc7227591","ms-five-star-quote|marketing/quote|4:5|pace=calm,look=dark":"aadc43361c7fcb6f","ms-five-star-quote|marketing/quote|4:5|pace=calm,look=brand":"abe4872b51c065f4","ms-five-star-quote|marketing/quote|4:5|pace=punchy,look=light":"d9bdf7c29fc81ebe","ms-five-star-quote|marketing/quote|4:5|pace=punchy,look=dark":"95a9d10450bbb761","ms-five-star-quote|marketing/quote|4:5|pace=punchy,look=brand":"69ec440d54a1738d","ms-end-card|end-card/draw-on|9:16|mark=logo":"cc4f14e8bc31e611","ms-end-card|end-card/draw-on|9:16|mark=name":"be2e4af57dbf745d","ms-end-card|end-card/draw-on|1:1|mark=logo":"bb89f5b132db8db4","ms-end-card|end-card/draw-on|1:1|mark=name":"ff9fc8df8575eb69","ms-end-card|end-card/draw-on|16:9|mark=logo":"f9c11d30ba4e00b6","ms-end-card|end-card/draw-on|16:9|mark=name":"af8b85d8d86a0fc5","ms-end-card|end-card/draw-on|4:5|mark=logo":"b0e8dac1210fa11c","ms-end-card|end-card/draw-on|4:5|mark=name":"36068519ba63f7f2","ms-end-card|end-card/rise|9:16|mark=logo":"cc0f15d0faacba78","ms-end-card|end-card/rise|9:16|mark=name":"fabe7b39ed33c7cc","ms-end-card|end-card/rise|1:1|mark=logo":"1b8ae510fece6edb","ms-end-card|end-card/rise|1:1|mark=name":"4a2588f06d3e1a3e","ms-end-card|end-card/rise|16:9|mark=logo":"e7fe344af3b40220","ms-end-card|end-card/rise|16:9|mark=name":"5c408aa6df00f14a","ms-end-card|end-card/rise|4:5|mark=logo":"944d19960c1c55e3","ms-end-card|end-card/rise|4:5|mark=name":"15234e56fe8079c4","ms-end-card|end-card/iris|9:16|mark=logo":"510b5f17815ec362","ms-end-card|end-card/iris|9:16|mark=name":"93443a5f128f1119","ms-end-card|end-card/iris|1:1|mark=logo":"3388cc3f925347b0","ms-end-card|end-card/iris|1:1|mark=name":"967ec6568e071ce7","ms-end-card|end-card/iris|16:9|mark=logo":"9eabff79866722b2","ms-end-card|end-card/iris|16:9|mark=name":"fc6d0499a473ffeb","ms-end-card|end-card/iris|4:5|mark=logo":"eb0b34afc8d595e6","ms-end-card|end-card/iris|4:5|mark=name":"a6a43281becaf07d","ms-end-card|end-card/split|9:16|mark=logo":"0c95e3b085e403e1","ms-end-card|end-card/split|9:16|mark=name":"31a8b6ee6c3ce985","ms-end-card|end-card/split|1:1|mark=logo":"6980bcf519b83860","ms-end-card|end-card/split|1:1|mark=name":"20bd8cb23bc67a93","ms-end-card|end-card/split|16:9|mark=logo":"54b050faac8fe276","ms-end-card|end-card/split|16:9|mark=name":"4bdab8dd6c08ce0d","ms-end-card|end-card/split|4:5|mark=logo":"6303668e0e25ec03","ms-end-card|end-card/split|4:5|mark=name":"4c52b36f016d740d","ms-end-card|end-card/glint|9:16|mark=logo":"a05b3508e1e880a8","ms-end-card|end-card/glint|9:16|mark=name":"34518253d1977e41","ms-end-card|end-card/glint|1:1|mark=logo":"6d30bfa7989dd816","ms-end-card|end-card/glint|1:1|mark=name":"c02dda49c89adc42","ms-end-card|end-card/glint|16:9|mark=logo":"59cc7ccc30e5c501","ms-end-card|end-card/glint|16:9|mark=name":"0b2dab7ca48af8da","ms-end-card|end-card/glint|4:5|mark=logo":"80c4d545a1e621c8","ms-end-card|end-card/glint|4:5|mark=name":"cd453e906341c932"}diff --git a/tests/generations-local-motion.test.ts b/tests/generations-local-motion.test.tsindex 795f8322..d1f9e857 100644--- a/tests/generations-local-motion.test.ts+++ b/tests/generations-local-motion.test.ts@@ -24,6 +24,7 @@ const { listGenerations, getGeneration } = await import("@/server/generations");const { hit } = await import("@/server/rate");const { RECIPE_MAX_BYTES } = await import("@/lib/motion/recipe");const { recipe } = await import("./helpers/motion");+const { designSize, exportSize } = await import("@/lib/motion/sizes");let moderation: http.Server | null = null;let answer: Record<string, unknown> = { allowed: true };@@ -239,3 +240,92 @@ describe("guests and the proxy", () => {expect((await call(body(ownerFile()))).status).toBe(401);});});++describe("Kinetic page results: frames, contact sheets, versions and a clip under the words", () => {+ /** A PNG's first bytes: the signature and an IHDR chunk with its size (enough for the route's size check). */+ const pngOf = (w: number, h: number) => {+ const ihdr = Buffer.alloc(25);+ ihdr.writeUInt32BE(13, 0);+ ihdr.write("IHDR", 4, "ascii");+ ihdr.writeUInt32BE(w, 8);+ ihdr.writeUInt32BE(h, 12);+ ihdr[16] = 8;+ ihdr[17] = 6;+ return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), ihdr, Buffer.alloc(100, 2)]);+ };+ /** The size a picture result of the default recipe (the draw-on end card) is made at. */+ const sizeFor = (feature: string) => {+ const r = recipe("end-card/draw-on");+ if (feature === "kinetic-version") {+ const d = designSize(r.size);+ const k = 540 / Math.max(d.w, d.h);+ return { w: Math.round(d.w * k), h: Math.round(d.h * k) };+ }+ const e = exportSize(r.size);+ return { w: e.w - (e.w % 2), h: e.h - (e.h % 2) };+ };+ const png = (accountId?: string, feature = "kinetic-frame", size = sizeFor(feature)) =>+ saveFile({ data: pngOf(size.w, size.h), contentType: "image/png", name: "k.png", source: "upload", ...(accountId && { accountId }) }).url;+ const picture = (url: string, feature: string, over: Record<string, unknown> = {}) => body(url, { feature, output: { url, kind: "image", contentType: "image/png" }, ...over });+ const layer = (src: string) => ({ src, from: 0, fit: "cover", dim: 0.2, scrim: "bottom" });++ it("records a frame, a contact sheet and a version as PNG pictures; a PNG is never a clip", async () => {+ for (const f of ["kinetic-frame", "kinetic-sheet", "kinetic-version"]) {+ const r = await call(picture(png(undefined, f), f), owner());+ expect(r.status, f).toBe(201);+ const o = (await r.json()).outputs[0];+ expect(o.kind).toBe("image");+ // Recorded with its size, so its tile shows it whole.+ expect({ w: o.width, h: o.height }, f).toEqual(sizeFor(f));+ }+ expect((await call(picture(png(), "kinetic"), owner())).status).toBe(400);+ // A clip recorded as a frame, and a frame stored as a clip, are refused.+ expect((await call(body(ownerFile(), { feature: "kinetic-frame" }), owner())).status).toBe(400);+ expect((await call(body(png(), { feature: "kinetic-frame", output: { url: png(), kind: "video", contentType: "video/mp4" } }), owner())).status).toBe(400);+ });++ it("takes a picture only at the size its recipe makes, and records a clip with its size", async () => {+ // Any other PNG (a picture that isn't this recipe's frame) is refused, as is one whose header can't be read.+ for (const f of ["kinetic-frame", "kinetic-sheet", "kinetic-version"]) {+ expect((await call(picture(png(undefined, f, { w: 640, h: 640 }), f), owner())).status, f).toBe(400);+ }+ const bare = saveFile({ data: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]), contentType: "image/png", name: "cut.png", source: "upload" }).url;+ expect((await call(picture(bare, "kinetic-frame"), owner())).status).toBe(400);+ const r = await call(body(ownerFile()), owner());+ expect(r.status).toBe(201);+ const o = (await r.json()).outputs[0];+ expect({ w: o.width, h: o.height }).toEqual(sizeFor("kinetic"));+ });++ it("takes only a stored video as the clip under the words", async () => {+ const picture = saveFile({ data: pngOf(64, 64), contentType: "image/png", name: "still.png", source: "upload" }).url;+ const motion = recipe("marketing/big-number", { layers: { video: layer(picture) } } as never);+ expect((await call(body(ownerFile(), { feature: "kinetic", params: { extra: { motion } } }), owner())).status).toBe(400);+ });++ it("takes a video input only when it is the recipe's own clip", async () => {+ const clip = ownerFile("video/mp4", "under.mp4");+ const motion = recipe("marketing/big-number", { layers: { video: layer(clip) } } as never);+ expect((await call(body(ownerFile(), { feature: "kinetic", inputs: { video: clip }, params: { extra: { motion } } }), owner())).status).toBe(201);+ expect((await call(body(ownerFile(), { feature: "kinetic", inputs: { video: ownerFile("video/mp4", "other.mp4") }, params: { extra: { motion } } }), owner())).status).toBe(400);+ });++ it("an account's clip under the words must be its own file", async () => {+ process.env.FUOBE_PUBLIC_SIGNUP = "1";+ const a = newAccount();+ const b = newAccount();+ const mine = accountFile(a.id, "video/mp4", "mine.mp4");+ const ok = await call(body(accountFile(a.id), { feature: "kinetic", inputs: { video: mine }, params: { extra: { motion: recipe("marketing/big-number", { layers: { video: layer(mine) } } as never) } } }), a.cookie);+ expect(ok.status).toBe(201);+ for (const theirs of [accountFile(b.id, "video/mp4", "theirs.mp4"), ownerFile("video/mp4", "owners.mp4")]) {+ const r = await call(body(accountFile(a.id), { feature: "kinetic", inputs: { video: theirs }, params: { extra: { motion: recipe("marketing/big-number", { layers: { video: layer(theirs) } } as never) } } }), a.cookie);+ expect(r.status).toBe(403);+ expect((await r.json()).error).toMatch(/can't find/);+ // Named in the recipe only, it is checked all the same.+ const r2 = await call(body(accountFile(a.id), { feature: "kinetic", params: { extra: { motion: recipe("marketing/big-number", { layers: { video: layer(theirs) } } as never) } } }), a.cookie);+ expect(r2.status).toBe(403);+ }+ // Its own frame as a picture result.+ expect((await call(picture(png(a.id, "kinetic-version"), "kinetic-version"), a.cookie)).status).toBe(201);+ });+});diff --git a/tests/kinetic-catalog.test.ts b/tests/kinetic-catalog.test.tsnew file mode 100644index 00000000..216fdd7c--- /dev/null+++ b/tests/kinetic-catalog.test.ts@@ -0,0 +1,111 @@+import { describe, expect, it } from "vitest";+import { TEMPLATES } from "@/lib/catalog/marketing";+import { CLIP_SCENES, groupDefsFor, groupMatches } from "@/lib/motion/kinetic-groups";+import { entryBySlug, entryForRecipe, exampleRecipe, KINETIC_EXAMPLES, KINETIC_SCENES, KINETIC_SLUGS, normalizeKinetic, restingTime, startRecipe, templateOf } from "@/lib/motion/kinetic-catalog";+import { loadScene } from "@/lib/motion/registry";+import { presetOf } from "@/lib/motion/edit";+import { templateLengths, templateSizes } from "@/lib/motion/template";+import { templateCover } from "@/lib/template-covers";+import { measure, RASTER_LOGO } from "./helpers/motion";++// The scene list bundled with /kinetic: ten scenes from the code templates, and every animation step of every scene in+// exactly one named motion group (so no visitor ever sees an internal id).++describe("the Kinetic scene catalogue", () => {+ it("has the ten scenes with their slugs and every template field", () => {+ expect(KINETIC_SLUGS.sort()).toEqual(["big-number", "end-card", "feature-cards", "kinetic-headline", "line-reveal", "logo-sting", "offer-badge", "quote", "starburst", "stat-dashboard"]);+ const code = TEMPLATES.filter((t) => t.render === "code").map((t) => t.id);+ expect(KINETIC_SCENES.map((e) => e.template).sort()).toEqual([...code].sort());+ for (const e of KINETIC_SCENES) {+ const t = templateOf(e);+ expect(e.name).toBe(t.name);+ expect(t.fields?.length, e.slug).toBeGreaterThan(0);+ expect(e.blurb.length).toBeGreaterThan(10);+ expect(e.groups.length).toBeGreaterThan(1);+ for (const g of e.groups) expect(g.label).not.toMatch(/^[a-z]+(\.|$)/);+ }+ expect(KINETIC_SCENES.find((e) => e.slug === "end-card")!.scenes).toHaveLength(5);+ expect(KINETIC_SCENES.filter((e) => e.clip).map((e) => e.slug).sort()).toEqual(["big-number", "feature-cards", "kinetic-headline", "logo-sting", "quote"]);+ expect(CLIP_SCENES).toHaveLength(5);+ });++ it("has four examples, each with a cover", () => {+ expect(KINETIC_EXAMPLES.map((x) => x.label)).toEqual(["Kinetic Headline", "Big Number", "Logo End Card", "Five-Star Quote"]);+ for (const x of KINETIC_EXAMPLES) expect(templateCover("marketing", entryBySlug(x.slug)!.template), x.slug).toBeTruthy();+ expect(KINETIC_EXAMPLES.find((x) => x.slug === "end-card")?.style).toBe("glint");+ });++ it("finishes each example with its own presets, in 4:5 where the scene offers it", () => {+ for (const x of KINETIC_EXAMPLES) {+ const r = exampleRecipe(x);+ expect(x.purpose.length, x.slug).toBeGreaterThan(10);+ expect(normalizeKinetic(r)?.entry.slug, x.slug).toBe(x.slug);+ // Different from the scene's own tile: a look, a feel or a camera of its own.+ expect(JSON.stringify(r), x.slug).not.toBe(JSON.stringify(startRecipe(entryBySlug(x.slug)!, { style: x.style })));+ if (x.presets.appearance) expect(presetOf("appearance", r), x.slug).toBe(x.presets.appearance);+ if (templateSizes(templateOf(entryBySlug(x.slug)!)).includes("4:5")) expect(r.size, x.slug).toBe("4:5");+ }+ });++ it("rests Kinetic Headline on its set headline, before its end card; other scenes on their last frame", async () => {+ const kh = startRecipe(entryBySlug("kinetic-headline")!);+ const plan = (await loadScene(kh.scene)).plan({ recipe: kh, measure, logo: null });+ const cut = plan.timeline.events.find((e) => e.id === "words.exit")!.start;+ expect(restingTime(plan, kh)).toBeLessThan(cut);+ expect(restingTime(plan, kh)).toBeGreaterThan(cut - 0.2);+ const big = startRecipe(entryBySlug("big-number")!);+ const bp = (await loadScene(big.scene)).plan({ recipe: big, measure, logo: null });+ expect(restingTime(bp, big)).toBe(bp.rest);+ });++ it("holds a custom size to the export sheet's rule wherever a recipe comes from", () => {+ const big = startRecipe(entryBySlug("big-number")!);+ for (const size of [{ w: 4096, h: 4096 }, { w: 2160, h: 2160 }, { w: 255, h: 600 }, { w: 1081, h: 1350 }]) expect(normalizeKinetic({ ...big, size }), JSON.stringify(size)).toBeNull();+ expect(normalizeKinetic({ ...big, size: { w: 1080, h: 1350 } })?.recipe.size).toEqual({ w: 1080, h: 1350 });+ });++ it("puts every event of every scene in exactly one group (all sizes, shortest and longest, with and without a logo and a picture)", async () => {+ let checked = 0;+ for (const e of KINETIC_SCENES) {+ const t = templateOf(e);+ const len = templateLengths(t);+ for (const scene of e.scenes) {+ const defs = groupDefsFor(scene);+ const sc = await loadScene(scene);+ for (const size of ["9:16", "1:1", "16:9", "4:5"] as const) {+ for (const duration of [len.min, len.max]) {+ for (const logo of [true, false]) {+ for (const picture of [true, false]) {+ const base = startRecipe(e);+ const r = { ...base, scene, size, duration, brand: { ...base.brand, ...(logo ? { logo: "/previews/logo.png" } : { logo: undefined }) } };+ if (!logo) delete r.brand.logo;+ const plan = sc.plan({ recipe: r, measure, logo: logo ? RASTER_LOGO : null, ...(picture && { images: { product: { w: 800, h: 1024 } }, outlines: { product: null } }) });+ for (const ev of plan.timeline.events) {+ const hits = groupMatches(defs, ev);+ expect(hits, `${scene} ${size} ${duration}s logo=${logo} pic=${picture}: ${ev.id}`).toHaveLength(1);+ }+ checked++;+ }+ }+ }+ }+ }+ }+ expect(checked).toBeGreaterThan(200);+ });++ it("opens a saved recipe on its scene, drops what the scene doesn't take, and refuses what isn't a scene", () => {+ const big = startRecipe(entryBySlug("big-number")!);+ expect(normalizeKinetic(big)?.entry.slug).toBe("big-number");+ const withClip = { ...startRecipe(entryBySlug("line-reveal")!), layers: { video: { src: "/api/files/x.mp4", from: 0, fit: "cover" as const, dim: 0, scrim: "none" as const } }, groups: { nope: { keys: [[0, 0], [1, 1]] as [number, number][], rate: 1.5 }, outline: { keys: [[0, 0], [1, 1]] as [number, number][], rate: 1.5 } } };+ const n = normalizeKinetic(withClip)!;+ expect(n.recipe.layers).toBeUndefined();+ expect(Object.keys(n.recipe.groups!)).toEqual(["outline"]);+ expect(normalizeKinetic({ ...big, scene: "marketing/nothing" })).toBeNull();+ expect(normalizeKinetic({ hello: 1 })).toBeNull();+ // Click to Ad's end cards (no template) open as Logo End Card.+ const card = { ...startRecipe(entryBySlug("end-card")!), controls: {}, size: { w: 720, h: 1280 }, fps: 24 as const, duration: 2.5 };+ expect(entryForRecipe(card)?.slug).toBe("end-card");+ expect(normalizeKinetic(card)?.recipe.size).toEqual({ w: 720, h: 1280 });+ });+});diff --git a/tests/kinetic-history.test.ts b/tests/kinetic-history.test.tsnew file mode 100644index 00000000..e0c745bd--- /dev/null+++ b/tests/kinetic-history.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from "vitest";+import { canRedo, canUndo, change, HISTORY_MAX, redo, restore, settle, startHistory, undo } from "@/components/kinetic/history";++// Kinetic's undo and redo for one visit: steps, gestures joined into one step, the 100-step cap, and a restored+// version putting what was open on the stack.++describe("Kinetic history", () => {+ it("undoes and redoes plain changes", () => {+ let h = startHistory({ a: 1 });+ h = change(h, { a: 2 });+ h = change(h, { a: 3 });+ expect(canUndo(h)).toBe(true);+ h = undo(h);+ expect(h.present).toEqual({ a: 2 });+ expect(canRedo(h)).toBe(true);+ h = redo(h);+ expect(h.present).toEqual({ a: 3 });+ // A new change clears what could be redone.+ h = change(undo(h), { a: 9 });+ expect(canRedo(h)).toBe(false);+ });++ it("joins a drag or typing into one step until it settles, and ignores a change that changes nothing", () => {+ let h = startHistory({ v: 0 });+ for (let i = 1; i <= 10; i++) h = change(h, { v: i }, { gesture: true });+ expect(h.past).toHaveLength(1);+ h = settle(h);+ h = change(h, { v: 11 }, { gesture: true });+ expect(h.past).toHaveLength(2);+ expect(change(h, { v: 11 })).toEqual({ ...h, open: false });+ expect(undo(undo(h)).present).toEqual({ v: 0 });+ });++ it("keeps at most 100 steps", () => {+ let h = startHistory(0);+ for (let i = 1; i <= HISTORY_MAX + 30; i++) h = change(h, i);+ expect(h.past).toHaveLength(HISTORY_MAX);+ expect(h.past[0]).toBe(30);+ });++ it("a restore puts what was open on the stack, so Undo brings it back", () => {+ let h = startHistory({ s: "open" });+ h = change(h, { s: "edited" }, { gesture: true });+ h = restore(h, { s: "version" });+ expect(h.present).toEqual({ s: "version" });+ expect(undo(h).present).toEqual({ s: "edited" });+ });+});diff --git a/tests/motion-edit.test.ts b/tests/motion-edit.test.tsnew file mode 100644index 00000000..a95ab269--- /dev/null+++ b/tests/motion-edit.test.ts@@ -0,0 +1,233 @@+import { describe, expect, it } from "vitest";+import { CURVE_SETS, CURVES, FIXED_CURVES, type CurveName } from "@/lib/motion/ease";+import {+ applyPreset,+ dropTrackKey,+ groupsOf,+ keyIndexAt,+ moveTrackKey,+ PRESETS,+ presetOf,+ putTrackKey,+ rateLimits,+ retime,+ setValue,+ shapeKeys,+ shotWindows,+ SHAPES,+ tidyRecipe,+ trackValue,+ warpOf,+ MIN_EVENT,+ TRACK_KEYS_MAX,+ TRACKS_MAX,+ type PresetCategory,+} from "@/lib/motion/edit";+import { groupDefsFor } from "@/lib/motion/kinetic-groups";+import { GroupTimingSchema, normalizeRecipe, RECIPE_MAX_BYTES, RecipeSchema, TRACK_IDS, TRACK_LIMITS, type Recipe } from "@/lib/motion/recipe";+import { loadScene } from "@/lib/motion/registry";+import { showcaseRecipe } from "@/lib/motion/showcase";+import { textNodes } from "@/lib/motion/display";+import { TEMPLATES } from "@/lib/catalog/marketing";+import { measure, RASTER_LOGO } from "./helpers/motion";++// Kinetic's editor on the timeline: warps, rates, group edits that move nothing else, presets, curve sets and tracks.++/** A small seeded random for the property checks. */+function prng(seed: number) {+ let s = seed >>> 0;+ return () => {+ s = (s * 1664525 + 1013904223) >>> 0;+ return s / 2 ** 32;+ };+}++function randomKeys(r: () => number): [number, number][] {+ const n = 2 + Math.floor(r() * 7);+ const us = [0, ...Array.from({ length: n - 2 }, () => 0.02 + r() * 0.96).sort((a, b) => a - b), 1];+ const ps = [0, ...Array.from({ length: n - 2 }, () => r()).sort((a, b) => a - b), 1];+ const keys: [number, number][] = us.map((u, i) => [u, ps[i]]);+ // Strictly rising u.+ return keys.filter((k, i) => i === 0 || k[0] > keys[i - 1][0]);+}++const plan = async (r: Recipe) => (await loadScene(r.scene)).plan({ recipe: r, measure, logo: r.brand.logo ? RASTER_LOGO : null, images: { product: { w: 800, h: 1024 } }, outlines: { product: null } });++const code = TEMPLATES.filter((t) => t.render === "code");+const showcases = () => code.map((t) => showcaseRecipe(t.id, t.scene!, t.lengths?.default ?? 5)!);++describe("warps", () => {+ it("are monotone, start at 0 and end at 1 for random valid keys", () => {+ const r = prng(7);+ for (let n = 0; n < 200; n++) {+ const keys = randomKeys(r);+ const w = warpOf(keys);+ expect(w(0)).toBe(0);+ expect(w(1)).toBe(1);+ let prev = 0;+ for (let i = 0; i <= 200; i++) {+ const v = w(i / 200);+ expect(Number.isFinite(v)).toBe(true);+ expect(v).toBeGreaterThanOrEqual(prev - 1e-12);+ prev = v;+ }+ }+ });++ it("the identity keys change nothing, and every suggested shape is valid", () => {+ const w = warpOf([+ [0, 0],+ [1, 1],+ ]);+ for (const u of [0, 0.1, 0.5, 0.93, 1]) expect(w(u)).toBe(u);+ for (const s of SHAPES) {+ const k = shapeKeys(s.id);+ expect(GroupTimingSchema.safeParse({ keys: k, rate: 1 }).success, s.id).toBe(true);+ }+ });+});++describe("motion groups", () => {+ it("a group edit never moves another group's events, the cuts, the words, the length or the last frame", async () => {+ for (const base of showcases()) {+ const before = await plan(base);+ const windows = shotWindows(before);+ const groups = groupsOf(groupDefsFor(base.scene), before.timeline.events, windows).filter((g) => !g.camera && !groupDefsFor(base.scene).find((d) => d.id === g.id)?.inner);+ for (const g of groups) {+ const lim = rateLimits(g, windows, before.rest);+ for (const rate of [lim.min, lim.max]) {+ const r: Recipe = { ...base, groups: { [g.id]: { keys: shapeKeys("in-out"), rate } } };+ const after = await plan(r);+ expect(after.cuts, `${base.scene} ${g.id}`).toEqual(before.cuts);+ expect(after.rest).toBe(before.rest);+ expect(JSON.stringify(after.evaluate(after.rest))).toBe(JSON.stringify(before.evaluate(before.rest)));+ expect(textNodes(after.evaluate(after.rest).nodes).map((t) => JSON.stringify(t.runs))).toEqual(textNodes(before.evaluate(before.rest).nodes).map((t) => JSON.stringify(t.runs)));+ const mine = new Set(g.events.map((e) => e.id));+ for (const e of before.timeline.events) {+ const x = after.timeline.byId.get(e.id)!;+ if (!mine.has(e.id)) expect([x.start, x.dur], `${base.scene} ${g.id} moved ${e.id}`).toEqual([e.start, e.dur]);+ else {+ expect(x.dur).toBeGreaterThanOrEqual(Math.min(e.dur, MIN_EVENT) - 1e-9);+ // Inside its shot, and a second before the last frame (unless the design itself ends later).+ const end = x.start + x.dur;+ const own = Math.max(...g.events.map((y) => y.start + y.dur));+ expect(end).toBeLessThanOrEqual(Math.max(Math.min(windows[g.window][1], before.rest - 1), own) + 1e-6);+ }+ }+ }+ }+ }+ });++ it("retime gives back the same events without timing", async () => {+ const base = showcases()[1];+ const p = await plan(base);+ const w = shotWindows(p);+ const g = groupsOf(groupDefsFor(base.scene), p.timeline.events, w);+ expect(retime(p.timeline.events, undefined, g, w, p.rest)).toBe(p.timeline.events);+ expect(retime(p.timeline.events, { number: { keys: shapeKeys("even"), rate: 1 } }, g, w, p.rest)).toBe(p.timeline.events);+ });+});++describe("presets", () => {+ const base = showcases()[1];+ it("at most 4 per category, 15 values each, all in their own category, the first the identity", () => {+ for (const [cat, list] of Object.entries(PRESETS) as [PresetCategory, (typeof PRESETS)["motion"]][]) {+ expect(list.length).toBeLessThanOrEqual(4);+ const prefix = cat === "appearance" ? "finish." : `${cat}.`;+ for (const p of list) {+ expect(Object.keys(p.values).length).toBeLessThanOrEqual(15);+ for (const k of Object.keys(p.values)) expect(k.startsWith(prefix), `${p.id} ${k}`).toBe(true);+ }+ expect(presetOf(cat, base)).toBe(list[0].id);+ expect(tidyRecipe(applyPreset(cat, list[0].id, base))).toEqual(base);+ }+ });++ it("a manual change reads Custom, and picking the preset again restores it", () => {+ const film = applyPreset("appearance", "film", base);+ expect(presetOf("appearance", film)).toBe("film");+ const moved = setValue(film, "finish.contrast", 0.2);+ expect(presetOf("appearance", moved)).toBe("custom");+ expect(applyPreset("appearance", "film", moved)).toEqual(film);+ expect(presetOf("camera", setValue(base, "camera.amount", 1.5))).toBe("custom");+ });+});++describe("curve sets", () => {+ it("every swapped curve runs from 0 to 1 with no NaN, and the fixed curves are never swapped", () => {+ for (const [id, set] of Object.entries(CURVE_SETS)) {+ for (const [name, f] of Object.entries(set) as [CurveName, (u: number) => number][]) {+ expect(FIXED_CURVES.includes(name), `${id} swaps ${name}`).toBe(false);+ expect(f(0)).toBeCloseTo(0, 9);+ expect(f(1)).toBeCloseTo(1, 9);+ for (let i = 0; i <= 1000; i++) expect(Number.isNaN(f(i / 1000))).toBe(false);+ }+ }+ expect(Object.keys(CURVE_SETS.smooth)).toHaveLength(0);+ expect(Object.keys(CURVES).length).toBeGreaterThan(5);+ });+});++describe("camera moves come home", () => {+ it("every move at amounts 0, 1 and 2 gives the home camera on the last frame", async () => {+ for (const base of showcases()) {+ const home = await plan(base);+ const rest = JSON.stringify(home.evaluate(home.rest));+ for (const move of ["scene", "locked", "push", "drift", "rise"] as const) {+ for (const amount of [0, 1, 2]) {+ const p = await plan({ ...base, camera: { move, amount } });+ expect(JSON.stringify(p.evaluate(p.rest)), `${base.scene} ${move} ${amount}`).toBe(rest);+ }+ }+ }+ });++ it("with camera tracks, the last frame and the still frame after it are equal", async () => {+ const base = showcases()[1];+ const r = putTrackKey(putTrackKey(base, "camera.zoom", 0, 1, base.fps)!, "camera.zoom", base.duration, 1.1, base.fps)!;+ const p = await plan(r);+ expect(JSON.stringify(p.evaluate(p.rest))).toBe(JSON.stringify(p.evaluate(p.rest + 1)));+ expect(JSON.stringify(p.evaluate(p.rest))).not.toBe(JSON.stringify((await plan(base)).evaluate(p.rest)));+ });+});++describe("tracks", () => {+ const base = showcases()[1];+ it("sample, hold before and after, and rate about the first key", () => {+ const tr = { keys: [{ t: 1, v: 0 }, { t: 3, v: 1, ease: "linear" as const }], rate: 1 };+ expect(trackValue(tr, 0)).toBe(0);+ expect(trackValue(tr, 5)).toBe(1);+ expect(trackValue(tr, 2)).toBeCloseTo(0.5, 6);+ expect(trackValue({ ...tr, rate: 2 }, 2)).toBeCloseTo(1, 6);+ });++ it("keys go in at the playhead, are found within half a frame, move and drop", () => {+ let r = putTrackKey(base, "finish.grain", 1, 0.05, 30)!;+ r = putTrackKey(r, "finish.grain", 2, 0.5, 30)!;+ expect(r.tracks!["finish.grain"]!.keys.map((k) => k.v)).toEqual([0.05, 0.1]);+ expect(keyIndexAt(r.tracks!["finish.grain"], 2 + 0.4 / 30, 30)).toBe(1);+ expect(keyIndexAt(r.tracks!["finish.grain"], 2 + 0.6 / 30, 30)).toBe(-1);+ r = moveTrackKey(r, "finish.grain", 0, 5, 30);+ expect(r.tracks!["finish.grain"]!.keys[0].t).toBeCloseTo(2 - 1 / 30, 4);+ r = dropTrackKey(dropTrackKey(r, "finish.grain", 0), "finish.grain", 0);+ expect(r.tracks).toBeUndefined();+ });++ it("at most 8 tracks of 16 keys, and the largest recipe stays under 64 KB", () => {+ let r: Recipe = base;+ for (let i = 0; i < TRACK_KEYS_MAX; i++) r = putTrackKey(r, "camera.zoom", i * 0.25, 1, 30)!;+ expect(putTrackKey(r, "camera.zoom", 4.5, 1, 30)).toBeNull();+ for (const id of TRACK_IDS) r = putTrackKey(r, id, 0, 0, 30) ?? r;+ expect(Object.keys(r.tracks!)).toHaveLength(TRACKS_MAX);+ const big: Recipe = {+ ...r,+ layers: { video: { src: "/api/files/a.mp4", from: 0, fit: "cover", dim: 0.2, scrim: "bottom" } },+ tracks: Object.fromEntries(TRACK_IDS.map((id) => [id, { keys: Array.from({ length: 16 }, (_, i) => ({ t: i * 0.3, v: TRACK_LIMITS[id][0], ease: "move" as const })), rate: 1 }])),+ groups: Object.fromEntries(Array.from({ length: 12 }, (_, i) => [`g${i}`, { keys: Array.from({ length: 8 }, (_, j) => [j / 7, j / 7] as [number, number]), rate: 1.5 }])),+ };+ expect(RecipeSchema.safeParse(big).success).toBe(true);+ expect(JSON.stringify(big).length).toBeLessThan(RECIPE_MAX_BYTES);+ expect(() => normalizeRecipe(big)).not.toThrow();+ });+});diff --git a/tests/motion-identity.test.ts b/tests/motion-identity.test.tsnew file mode 100644index 00000000..0e2a7acb--- /dev/null+++ b/tests/motion-identity.test.ts@@ -0,0 +1,86 @@+import { createHash } from "node:crypto";+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { TEMPLATES } from "@/lib/catalog/marketing";+import { stableJson, type Recipe } from "@/lib/motion/recipe";+import { loadScene, SCENE_IDS } from "@/lib/motion/registry";+import { showcaseRecipe } from "@/lib/motion/showcase";+import { measure, RASTER_LOGO } from "./helpers/motion";++// Kinetic's editor adds optional recipe fields. A recipe without them (or with every one at its default: the first+// preset of each category, identity group timing and no tracks) must draw exactly what phase 2 drew: every scene, size+// and Easy choice at 12 times, the rest frame included. The fixture holds a hash of those display lists made on the+// phase 2 code (UPDATE_MOTION_IDENTITY=1 writes it; only ever from a checkout without the editor's changes), apart+// from Kinetic Headline, whose end card later gained the ground's light (its keys were written again then, alone).++const FIXTURE = path.join(process.cwd(), "tests/fixtures/motion-identity.json");+const WRITE = process.env.UPDATE_MOTION_IDENTITY === "1";++const code = TEMPLATES.filter((t) => t.render === "code");++interface Case {+ key: string;+ recipe: Recipe;+}++function cases(): Case[] {+ const out: Case[] = [];+ for (const t of code) {+ const scenes = t.scene!.startsWith("end-card/") ? SCENE_IDS.filter((s) => s.startsWith("end-card/")) : [t.scene!];+ const groups = (t.easy ?? []).filter((g) => !g.scene);+ // Every combination of the template's own Easy choices.+ let combos: Record<string, string>[] = [{}];+ for (const g of groups) combos = combos.flatMap((c) => g.choices.map((ch) => ({ ...c, [g.id]: ch.id })));+ for (const scene of scenes) {+ for (const size of ["9:16", "1:1", "16:9", "4:5"] as const) {+ for (const c of combos) {+ const base = showcaseRecipe(t.id, scene, t.lengths?.default ?? 5)!;+ const recipe: Recipe = { ...base, scene, size, controls: { ...base.controls, ...c } };+ if (c.mark === "name") delete recipe.brand.logo;+ out.push({ key: `${t.id}|${scene}|${size}|${Object.entries(c).map(([k, v]) => `${k}=${v}`).join(",")}`, recipe });+ }+ }+ }+ }+ return out;+}++async function hashOf(r: Recipe): Promise<string> {+ const scene = await loadScene(r.scene);+ const plan = scene.plan({ recipe: r, measure, logo: r.brand.logo ? RASTER_LOGO : null, images: { product: { w: 800, h: 1024 } }, outlines: { product: null } });+ const h = createHash("sha1");+ for (let i = 0; i < 12; i++) h.update(stableJson(plan.evaluate((i / 11) * plan.rest)));+ h.update(stableJson(plan.timeline.events.map((e) => [e.id, e.start, e.dur])));+ return h.digest("hex").slice(0, 16);+}++/** Every editor field at its default value. */+function withDefaults(r: Recipe): Recipe {+ return {+ ...r,+ motion: { curves: "smooth" },+ finish: { contrast: 0, saturation: 0, grain: 0, grainSize: 1.2 },+ camera: { move: "scene", amount: 1, breath: 1 },+ look: { light: true },+ groups: { camera: { keys: [[0, 0], [1, 1]], rate: 1 } },+ };+}++describe("a recipe without the editor's changes draws exactly what phase 2 drew", () => {+ it("holds for every scene, size and Easy choice, at 12 times", async () => {+ const all = cases();+ expect(all.length).toBeGreaterThan(200);+ const got: Record<string, string> = {};+ for (const c of all) got[c.key] = await hashOf(c.recipe);+ if (WRITE) {+ fs.writeFileSync(FIXTURE, `${JSON.stringify(got, null, 0)}\n`);+ return;+ }+ const want = JSON.parse(fs.readFileSync(FIXTURE, "utf8")) as Record<string, string>;+ expect(Object.keys(got).sort()).toEqual(Object.keys(want).sort());+ for (const c of all) expect(got[c.key], c.key).toBe(want[c.key]);+ // Every editor field at its default changes nothing either.+ for (const c of all) expect(await hashOf(withDefaults(c.recipe)), `${c.key} with defaults`).toBe(want[c.key]);+ });+});diff --git a/tests/motion-kinetic-layers.test.ts b/tests/motion-kinetic-layers.test.tsnew file mode 100644index 00000000..202d11f7--- /dev/null+++ b/tests/motion-kinetic-layers.test.ts@@ -0,0 +1,129 @@+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { TEMPLATES } from "@/lib/catalog/marketing";+import { videoNodeOf } from "@/lib/motion/display";+import { cssFilter, finishAt, gradePixels, grainOffset, grainTile, neutralFinish } from "@/lib/motion/finish";+import { entryBySlug, startRecipe } from "@/lib/motion/kinetic-catalog";+import { normalizeRecipe, recipeKey, RecipeSchema, type Recipe } from "@/lib/motion/recipe";+import { loadScene } from "@/lib/motion/registry";+import { showcaseRecipe } from "@/lib/motion/showcase";+import { exportBitrate } from "@/lib/motion/sizes";+import { clipBox, clipTime } from "@/lib/motion/video-layer";+import { measure, RASTER_LOGO } from "./helpers/motion";++// The recipe's new layers: old recipes still read, the finish (grade and grain), the clip under the words, and the+// preview modes never reaching a saved file.++const CLIP = { w: 1920, h: 1080, duration: 2 };+const layer = { src: "/api/files/clip.mp4", from: 0.5, fit: "cover" as const, dim: 0.3, scrim: "bottom" as const };+const plan = async (r: Recipe, clip = true) => (await loadScene(r.scene)).plan({ recipe: r, measure, logo: RASTER_LOGO, ...(clip && { clips: { clip: CLIP } }) });++describe("recipe compatibility", () => {+ it("every phase 1 and 2 recipe still parses and normalises unchanged", () => {+ for (const t of TEMPLATES.filter((x) => x.render === "code")) {+ const r = showcaseRecipe(t.id, t.scene!, t.lengths?.default ?? 5)!;+ expect(normalizeRecipe(r)).toEqual(r);+ expect(RecipeSchema.parse(r)).toEqual(r);+ }+ const card: Recipe = { v: 1, scene: "end-card/glint", seed: 1, size: { w: 720, h: 1280 }, fps: 25, duration: 2.5, fields: { brand: "Aurèle", product: "Le Sérum" }, brand: { name: "Aurèle", colors: ["#123456"], fonts: { heading: "Inter", body: "Inter" } }, export: { format: "mp4", blurSamples: 8, shutter: 180 } };+ expect(normalizeRecipe(card)).toEqual(card);+ });++ it("drops a clip on a scene that doesn't take one and unknown group ids, never failing", () => {+ const r = { ...startRecipe(entryBySlug("starburst")!), layers: { video: layer }, groups: { zzz: { keys: [[0, 0], [1, 1]] as [number, number][], rate: 2 } }, tracks: { "clip.dim": { keys: [{ t: 0, v: 0.2 }], rate: 1 } } };+ const out = normalizeRecipe(r, undefined, { clip: false, groups: ["burst"] });+ expect(out.layers).toBeUndefined();+ expect(out.groups).toBeUndefined();+ expect(out.tracks).toBeUndefined();+ });++ it("takes 60 fps and High quality within the size cap", () => {+ expect(RecipeSchema.safeParse({ ...startRecipe(entryBySlug("big-number")!), fps: 60 }).success).toBe(true);+ const std = exportBitrate("9:16", 5);+ expect(exportBitrate("9:16", 5, { fps: 60 })).toBe(Math.round(std * 1.5));+ expect(exportBitrate("9:16", 5, { quality: "high" })).toBe(Math.round(std * 1.6));+ expect(exportBitrate("9:16", 60, { fps: 60, quality: "high" })).toBeLessThanOrEqual(Math.floor((0.6 * 95 * 1024 * 1024 * 8) / 60));+ });+});++describe("the finish", () => {+ const base = startRecipe(entryBySlug("big-number")!);+ it("a neutral finish is the identity", () => {+ expect(finishAt(base, 1)).toBeNull();+ expect(finishAt({ ...base, finish: { contrast: 0, saturation: 0, grain: 0, grainSize: 2 } }, 1)).toBeNull();+ expect(cssFilter({ contrast: 0, saturation: 0 })).toBe("none");+ const px = new Uint8ClampedArray([10, 200, 90, 255]);+ gradePixels(px, { contrast: 0, saturation: 0 });+ expect([...px]).toEqual([10, 200, 90, 255]);+ expect(neutralFinish({ contrast: 0, saturation: 0, grain: 0 })).toBe(true);+ });++ it("the pixel pass follows the filter formulas (contrast about mid grey, saturate's matrix)", () => {+ const px = new Uint8ClampedArray([200, 100, 50, 255]);+ gradePixels(px, { contrast: 0.2, saturation: 0 });+ expect([...px.slice(0, 3)]).toEqual([Math.round(((200 / 255 - 0.5) * 1.2 + 0.5) * 255), Math.round(((100 / 255 - 0.5) * 1.2 + 0.5) * 255), Math.round(((50 / 255 - 0.5) * 1.2 + 0.5) * 255)]);+ const grey = new Uint8ClampedArray([200, 100, 50, 255]);+ gradePixels(grey, { contrast: 0, saturation: -1 });+ const l = 0.213 * 200 + 0.715 * 100 + 0.072 * 50;+ for (const c of grey.slice(0, 3)) expect(Math.abs(c - l)).toBeLessThanOrEqual(1);+ expect(cssFilter({ contrast: 0.08, saturation: -0.05 })).toBe("contrast(1.0800) saturate(0.9500)");+ });++ it("grain is the same for the same seed and frame, and differs between frames", () => {+ expect(grainTile(7)).toEqual(grainTile(7));+ expect(grainTile(7)).not.toEqual(grainTile(8));+ expect(grainOffset(7, 3)).toEqual(grainOffset(7, 3));+ expect(grainOffset(7, 3)).not.toEqual(grainOffset(7, 4));+ const f = finishAt({ ...base, finish: { grain: 0.03 } }, 1)!;+ expect(f.frame).toBe(30);+ expect(finishAt({ ...base, finish: { grain: 0.03 } }, 1.5)!.frame).toBe(45);+ });++ it("a finish track replaces the slider's value", () => {+ const r: Recipe = { ...base, finish: { contrast: 0.1 }, tracks: { "finish.contrast": { keys: [{ t: 0, v: 0.3 }], rate: 1 } } };+ expect(finishAt(r, 2)!.contrast).toBe(0.3);+ });+});++describe("the clip under the words", () => {+ const big: Recipe = { ...startRecipe(entryBySlug("big-number")!), layers: { video: layer } };+ it("draws the clip first, outside the camera, with no ground, its dim and its scrim", async () => {+ const p = await plan(big);+ const l = p.evaluate(1);+ const v = videoNodeOf(l)!;+ expect(v).toBeTruthy();+ expect(l.background).toBe("#000000");+ expect(l.nodes[1].type).toBe("rect");+ expect(l.nodes.find((n) => n.type === "group" && n.id === "camera")).toBeTruthy();+ expect(v.time).toBeCloseTo(1.5, 6);+ // Held on its last frame when the clip is shorter.+ expect(videoNodeOf(p.evaluate(p.rest))!.time).toBeLessThan(CLIP.duration);+ expect(videoNodeOf(p.evaluate(p.rest))!.time).toBeGreaterThan(CLIP.duration - 0.01);+ });++ it("cover fills and crops, contain shows all of it", () => {+ expect(clipBox({ w: 1920, h: 1080 }, { w: 1080, h: 1920 }, "cover")).toEqual({ x: (1080 - 1920 * (1920 / 1080)) / 2, y: 0, w: 1920 * (1920 / 1080), h: 1920 });+ const c = clipBox({ w: 1920, h: 1080 }, { w: 1080, h: 1920 }, "contain");+ expect(c.w).toBe(1080);+ expect(c.y).toBeGreaterThan(0);+ expect(clipTime({ from: 0.5 }, { duration: 10 }, 1.25)).toBe(1.75);+ });++ it("only the five clip scenes take a clip", async () => {+ const star = await plan({ ...startRecipe(entryBySlug("starburst")!), layers: { video: layer } });+ expect(videoNodeOf(star.evaluate(1))).toBeUndefined();+ const none = await plan(big, false);+ expect(videoNodeOf(none.evaluate(1))).toBeUndefined();+ });+});++describe("preview modes", () => {+ it("never reach the render or the recipe", () => {+ const render = fs.readFileSync(path.join(process.cwd(), "src/components/motion/render.ts"), "utf8");+ const recipe = fs.readFileSync(path.join(process.cwd(), "src/lib/motion/recipe.ts"), "utf8");+ for (const src of [render, recipe]) expect(src).not.toMatch(/previewMode|PreviewMode|PREVIEW_MODE|"balanced"|"sharp"/);+ const r = startRecipe(entryBySlug("big-number")!);+ expect(recipeKey(r)).toBe(recipeKey(JSON.parse(JSON.stringify(r))));+ });+});diff --git a/tests/motion-no-direct-download.test.ts b/tests/motion-no-direct-download.test.tsindex 84324df4..4f6bb584 100644--- a/tests/motion-no-direct-download.test.ts+++ b/tests/motion-no-direct-download.test.ts@@ -10,7 +10,7 @@ const files = (dir: string): string[] =>fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }).flatMap((d) => (d.isDirectory() ? files(path.join(dir, d.name)) : /\.(ts|tsx)$/.test(d.name) ? [path.join(dir, d.name)] : [])) : [];describe("no direct download of a motion render", () => {- const sources = [...files(path.join(ROOT, "src/components/motion")), ...files(path.join(ROOT, "src/lib/motion")), path.join(ROOT, "src/components/marketing/end-card-motion.tsx")];+ const sources = [...files(path.join(ROOT, "src/components/motion")), ...files(path.join(ROOT, "src/components/kinetic")), ...files(path.join(ROOT, "src/lib/motion")), path.join(ROOT, "src/components/marketing/end-card-motion.tsx"), path.join(ROOT, "src/components/canvas/kinetic-node.tsx")];it("finds the motion code", () => {expect(sources.length).toBeGreaterThan(15);diff --git a/tests/nav-bar.test.ts b/tests/nav-bar.test.tsindex bfa01bba..bb10e97d 100644--- a/tests/nav-bar.test.ts+++ b/tests/nav-bar.test.ts@@ -142,11 +142,11 @@ describe("which bar item holds the page", () => {describe("the launcher's columns", () => {const html = render(createElement(LauncherColumns, { kind: undefined, now: Date.parse("2026-11-02") }));- it("shows every studio, Apps and the Sound column, 8/6/5/6/5/3, each column's lead first", () => {+ it("shows every studio, Apps and the Sound column, 8/6/6/6/5/3, each column's lead first", () => {const links = hrefs(html);- expect(links).toHaveLength(33);- expect(new Set(links).size).toBe(33);- expect(launcherColumns(undefined).map((c) => 1 + c.rest.length)).toEqual([8, 6, 5, 6, 5, 3]);+ expect(links).toHaveLength(34);+ expect(new Set(links).size).toBe(34);+ expect(launcherColumns(undefined).map((c) => 1 + c.rest.length)).toEqual([8, 6, 6, 6, 5, 3]);expect(launcherColumns(undefined).map((c) => c.lead.id)).toEqual(["cinema", "shorts", "marketing", "fashion-factory", "audio", "upscale"]);expect(html).toContain("grid-cols-6");for (const [i, c] of launcherColumns(undefined).entries()) {@@ -154,7 +154,7 @@ describe("the launcher's columns", () => {expect(at(c.lead.href)).toContain(`data-col="${i}" data-row="0"`);c.rest.forEach((e, r) => expect(at(e.href), e.id).toContain(`data-col="${i}" data-row="${r + 1}"`));}- expect(studioCount()).toBe(28);+ expect(studioCount()).toBe(29);});it("labels the groups, and every link has its studio's real cover in a box of fixed size", () => {@@ -171,7 +171,7 @@ describe("the launcher's columns", () => {}// The six lead cards load as the panel warms; a row's picture when the row shows (lazy).expect(count(html, 'loading="eager"')).toBe(6);- expect(count(html, 'alt=""')).toBe(33);+ expect(count(html, 'alt=""')).toBe(34);});it("marks the open page's studio, and nothing else", () => {diff --git a/tests/nav-model.test.ts b/tests/nav-model.test.tsindex b3de8237..85b11b9b 100644--- a/tests/nav-model.test.ts+++ b/tests/nav-model.test.ts@@ -205,15 +205,15 @@ describe("nav model: entries", () => {});describe("nav model: launcher", () => {- it("has 28 studios, Apps and four Audio modes in six columns of 8, 6, 5, 6, 5 and 3, one lead each", () => {- expect(studioCount()).toBe(28);+ it("has 29 studios, Apps and four Audio modes in six columns of 8, 6, 6, 6, 5 and 3, one lead each", () => {+ expect(studioCount()).toBe(29);const cols = launcherColumns("owner");expect(cols.map((c) => c.group.id)).toEqual(["film", "social", "sell", "people", "sound", "finish"]);- expect(cols.map((c) => 1 + c.rest.length)).toEqual([8, 6, 5, 6, 5, 3]);+ expect(cols.map((c) => 1 + c.rest.length)).toEqual([8, 6, 6, 6, 5, 3]);expect(cols.map((c) => c.lead.id)).toEqual(["cinema", "shorts", "marketing", "fashion-factory", "audio", "upscale"]);for (const g of LAUNCHER_GROUPS) expect(NAV_ENTRIES.filter((e) => e.group === g.id && e.lead)).toHaveLength(1);- expect(launcherEntries("guest")).toHaveLength(33);- expect(launcherEntries("guest", "sell").map((e) => e.id)).toEqual(["marketing", "ads", "mixed-media", "moodboards", "photodump"]);+ expect(launcherEntries("guest")).toHaveLength(34);+ expect(launcherEntries("guest", "sell").map((e) => e.id)).toEqual(["marketing", "ads", "kinetic", "mixed-media", "moodboards", "photodump"]);expect(launcherEntries(undefined, "finish").map((e) => e.id)).toEqual(["upscale", "image-to-3d", "apps"]);// Sound: the Audio studio, then voice's neighbours (music, sound effects, clean-up, translate & dub); Lipsync stays in Social.expect(launcherEntries(undefined, "sound").map((e) => e.href)).toEqual(["/audio", "/audio/music", "/audio/sfx", "/audio/clean", "/audio/translate"]);@@ -225,7 +225,7 @@ describe("nav model: launcher", () => {expect(entry("storyboard")?.group).toBe("film");});- it("shows the same 33 to everyone", () => {+ it("shows the same 34 to everyone", () => {for (const k of KINDS) expect(launcherEntries(k).map((e) => e.id)).toEqual(launcherEntries("owner").map((e) => e.id));});});diff --git a/tests/phone-nav.test.ts b/tests/phone-nav.test.tsindex 6a396faa..dbc1493c 100644--- a/tests/phone-nav.test.ts+++ b/tests/phone-nav.test.ts@@ -189,11 +189,11 @@ describe("the Studios sheet", () => {// The grid ends on a See all tile (/studios): the family's whole set.const tiles = (html: string) => hrefs(html).filter((h) => h !== "/" && h !== "/library" && h !== "/studios");- it("shows every studio, Apps and the Sound modes (33 tiles, 28 studios), in launcher order, each with a real cover", () => {+ it("shows every studio, Apps and the Sound modes (34 tiles, 29 studios), in launcher order, each with a real cover", () => {const html = at("/", () => sheet());const all = launcherEntries(undefined);- expect(all).toHaveLength(33);- expect(studioCount()).toBe(28);+ expect(all).toHaveLength(34);+ expect(studioCount()).toBe(29);expect(tiles(html)).toEqual(all.map((e) => e.href));for (const e of all) {expect(e.cover, e.id).toBeTruthy();@@ -227,7 +227,7 @@ describe("the Studios sheet", () => {});it("starts on the group it was opened for", () => {- const sizes = { film: 8, social: 6, sell: 5, people: 6, sound: 5, finish: 3 } as const;+ const sizes = { film: 8, social: 6, sell: 6, people: 6, sound: 5, finish: 3 } as const;for (const g of LAUNCHER_GROUPS) {const html = at("/", () => sheet({ group: g.id }));expect(tiles(html), g.id).toEqual(launcherEntries(undefined, g.id).map((e) => e.href));diff --git a/tests/search-palette.test.ts b/tests/search-palette.test.tsindex a95baef9..ab19abd7 100644--- a/tests/search-palette.test.ts+++ b/tests/search-palette.test.ts@@ -150,13 +150,13 @@ describe("the palette's body", () => {expect(order.every((i) => i >= 0)).toBe(true);expect(order).toEqual([...order].sort((a, b) => a - b));expect(html.indexOf("Every studio")).toBeGreaterThan(html.indexOf("Also try"));- expect(tiles(html)).toHaveLength(33);+ expect(tiles(html)).toHaveLength(34);});it("starts filtered to a goal when opened for one", () => {const html = body("", "sell");- expect(tiles(html)).toEqual(["Marketing Studio", "Ads Studio", "Mixed Media", "Moodboards", "Photodump"]);- expect(html).toContain("5 in Sell & advertise");+ expect(tiles(html)).toEqual(["Marketing Studio", "Ads Studio", "Fuobe Kinetic Motion", "Mixed Media", "Moodboards", "Photodump"]);+ expect(html).toContain("6 in Sell & advertise");});it("starts on the best match, or on the first studio when nothing is typed", () => {