Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(cli): check warns when a tween ends just after a later tween on the same property (#5521)
James Russo69f33064156a
diff --git a/packages/cli/src/utils/checkBrowser.ts b/packages/cli/src/utils/checkBrowser.tsindex 3793aac7f3..d0ca97386c 100644--- a/packages/cli/src/utils/checkBrowser.ts+++ b/packages/cli/src/utils/checkBrowser.ts@@ -23,6 +23,7 @@ import { normalizeErrorMessage } from "./errorMessage.js";import { ambiguousIssue, type MotionFrame } from "./motionAudit.js";import type { LayoutIssue, LayoutIssueCode, LayoutRect } from "./layoutAudit.js";import { serveStaticProjectHtml } from "./staticProjectServer.js";+import { collectTweenRecords, findTweenTails, tweenTailMessage } from "./gsapTweenTails.js";import { resolveAutoProxy } from "./projectConfig.js";import {decideMediaProxyEligibility,@@ -231,6 +232,10 @@ export async function runBrowserCheck(for (const entry of await auditClipDurations(page, analyzeClipMediaFit, options.timeout)) {drafts.push({ code: "clip_media_fit", severity: entry.level, message: entry.text, time: 0 });}+ for (const tail of findTweenTails((await page.evaluate(collectTweenRecords)) ?? [])) {+ const message = tweenTailMessage(tail);+ drafts.push({ code: "gsap_tween_tail", severity: "warning", message, time: tail.later.end });+ }const driver = createPageDriver(page, (time) => {currentTime = time;});diff --git a/packages/cli/src/utils/gsapTweenTails.test.ts b/packages/cli/src/utils/gsapTweenTails.test.tsnew file mode 100644index 0000000000..a89c7f0625--- /dev/null+++ b/packages/cli/src/utils/gsapTweenTails.test.ts@@ -0,0 +1,123 @@+// @vitest-environment happy-dom+import { afterEach, describe, expect, it } from "vitest";+import { collectTweenRecords, findTweenTails, type TweenRecord } from "./gsapTweenTails.js";++const record = (start: number, end: number, overrides: Partial<TweenRecord> = {}): TweenRecord => ({+ timeline: "main",+ target: 0,+ label: "#word",+ properties: ["x"],+ start,+ end,+ ...overrides,+});++describe("findTweenTails", () => {+ it("flags a drift that ends 20 ms after the exit on the same property", () => {+ // The banner: enter, drift to x: -40 until 12.555 s, exit to x: 2200 from 12.335 s to 12.535 s.+ const tails = findTweenTails([record(11.855, 12.555), record(12.335, 12.535)]);+ expect(tails).toEqual([+ expect.objectContaining({+ properties: ["x"],+ earlier: { start: 11.855, end: 12.555 },+ later: { start: 12.335, end: 12.535 },+ }),+ ]);+ });++ it("leaves a slow drift that resumes long after a short move", () => {+ expect(findTweenTails([record(0, 4), record(1, 1.5)])).toEqual([]);+ });++ it("leaves tweens on other properties, other targets and other timelines", () => {+ const drift = record(11.855, 12.555);+ expect(findTweenTails([drift, record(12.335, 12.535, { properties: ["opacity"] })])).toEqual(+ [],+ );+ expect(findTweenTails([drift, record(12.335, 12.535, { target: 1 })])).toEqual([]);+ expect(findTweenTails([drift, record(12.335, 12.535, { timeline: "other" })])).toEqual([]);+ });++ it("leaves a later tween that ends after the earlier one", () => {+ expect(findTweenTails([record(0, 1), record(0.5, 1.2)])).toEqual([]);+ });+});++type FakeAnimation = {+ vars: Record<string, unknown>;+ parent: FakeAnimation | null;+ targets: () => unknown[];+ totalDuration: () => number;+ globalTime: (localTime: number) => number;+ getChildren?: () => FakeAnimation[];+};++function fakeTimeline(at: number, parent: FakeAnimation | null = null): FakeAnimation {+ const children: FakeAnimation[] = [];+ const timeline: FakeAnimation = {+ vars: {},+ parent,+ targets: () => [],+ totalDuration: () => 0,+ globalTime: (local) => at + local,+ getChildren: () =>+ children.flatMap((child) => (child.getChildren ? [child, ...child.getChildren()] : [child])),+ };+ return Object.assign(timeline, {+ add(child: FakeAnimation) {+ children.push(child);+ return child;+ },+ });+}++function fakeTween(+ parent: FakeAnimation & { add?: (child: FakeAnimation) => FakeAnimation },+ target: unknown,+ vars: Record<string, unknown>,+ start: number,+): FakeAnimation {+ const duration = Number(vars.duration);+ const tween: FakeAnimation = {+ vars,+ parent,+ targets: () => [target],+ totalDuration: () => duration,+ globalTime: (local) => parent.globalTime(start) + local,+ };+ return parent.add!(tween);+}++describe("collectTweenRecords", () => {+ afterEach(() => {+ delete (window as unknown as { __timelines?: unknown }).__timelines;+ document.body.innerHTML = "";+ });++ it("times each tween on its registered timeline and labels its target", () => {+ const word = document.body.appendChild(document.createElement("div"));+ word.className = "fx-bword";+ const main = fakeTimeline(100);+ const scene = fakeTimeline(110.4, main);+ (main as unknown as { add: (child: FakeAnimation) => void }).add(scene);+ fakeTween(scene, word, { x: -40, duration: 0.7, ease: "none" }, 1.455);+ fakeTween(scene, word, { x: 2200, duration: 0.2, ease: "expo.in" }, 1.935);+ fakeTween(scene, word, { x: 0, duration: 1, repeat: 2 }, 3);+ (window as unknown as { __timelines: Record<string, unknown> }).__timelines = { main, scene };++ const records = collectTweenRecords();+ expect(records.map(({ timeline, label, properties }) => [timeline, label, properties])).toEqual(+ [+ ["main", "div.fx-bword", ["x"]],+ ["main", "div.fx-bword", ["x"]],+ ],+ );+ expect(records[0]!.start).toBeCloseTo(11.855, 6);+ expect(records[0]!.end).toBeCloseTo(12.555, 6);+ expect(findTweenTails(records)).toHaveLength(1);+ });++ it("returns nothing when no timeline is registered", () => {+ expect(collectTweenRecords()).toEqual([]);+ });+});diff --git a/packages/cli/src/utils/gsapTweenTails.ts b/packages/cli/src/utils/gsapTweenTails.tsnew file mode 100644index 0000000000..8c028b09c1--- /dev/null+++ b/packages/cli/src/utils/gsapTweenTails.ts@@ -0,0 +1,161 @@+/**+ * A GSAP tween that ends just after a later tween on the same property takes the property back for that tail+ * and leaves its own end value on screen. A banner word whose drift (x: -40) ended 20 ms after its exit+ * (x: 2200) stayed in the middle of the frame for the rest of the scene, in playback and in renders alike.+ */++/** Seconds: a longer tail reads as an intended drift that resumes, not a tail the author missed. */+const TWEEN_TAIL_WINDOW = 0.25;++export interface TweenRecord {+ timeline: string;+ target: number;+ label: string;+ properties: string[];+ start: number;+ end: number;+}++export interface TweenTail {+ timeline: string;+ label: string;+ properties: string[];+ earlier: { start: number; end: number };+ later: { start: number; end: number };+}++export function findTweenTails(records: TweenRecord[]): TweenTail[] {+ return records.flatMap((earlier) =>+ records.flatMap((later) => {+ const tail = tailBetween(earlier, later);+ return tail ? [tail] : [];+ }),+ );+}++function tailBetween(earlier: TweenRecord, later: TweenRecord): TweenTail | null {+ if (later.target !== earlier.target || later.timeline !== earlier.timeline) return null;+ const overlaps = earlier.start < later.start && later.start < earlier.end;+ const tail = earlier.end - later.end;+ if (!overlaps || tail <= 0 || tail > TWEEN_TAIL_WINDOW) return null;+ const properties = earlier.properties.filter((name) => later.properties.includes(name));+ if (properties.length === 0) return null;+ return {+ timeline: earlier.timeline,+ label: earlier.label,+ properties,+ earlier: { start: earlier.start, end: earlier.end },+ later: { start: later.start, end: later.end },+ };+}++export function tweenTailMessage(tail: TweenTail): string {+ const props = tail.properties.join(", ");+ const seconds = (value: number) => `${value.toFixed(3)} s`;+ return (+ `In timeline "${tail.timeline}", a tween on ${props} of ${tail.label} ends at ${seconds(tail.earlier.end)}, ` ++ `${(tail.earlier.end - tail.later.end).toFixed(3)} s after a later tween on ${props} ends at ` ++ `${seconds(tail.later.end)}. For that tail the earlier tween takes ${props} back and leaves its own end value ` ++ `on screen, so the later tween's end never shows. End the earlier tween by ${seconds(tail.later.start)}, or ` ++ `add overwrite: "auto" to the later tween.`+ );+}++/**+ * Runs in the page (serialized by puppeteer, so it is self-contained): every plain tween of every registered+ * timeline, timed on that timeline. Repeating, yoyo, keyframed and overwrite tweens are left out.+ */+export function collectTweenRecords(): TweenRecord[] {+ type Tween = {+ vars: Record<string, unknown>;+ parent: Tween | null;+ targets: () => unknown[];+ totalDuration: () => number;+ globalTime: (localTime: number) => number;+ getChildren?: (nested: boolean, tweens: boolean, timelines: boolean) => Tween[];+ };+ const NOT_PROPERTIES = new Set([+ "duration",+ "delay",+ "ease",+ "repeat",+ "repeatDelay",+ "repeatRefresh",+ "yoyo",+ "yoyoEase",+ "stagger",+ "overwrite",+ "immediateRender",+ "lazy",+ "paused",+ "reversed",+ "runBackwards",+ "startAt",+ "keyframes",+ "inherit",+ "data",+ "id",+ "callbackScope",+ "onStart",+ "onStartParams",+ "onUpdate",+ "onUpdateParams",+ "onComplete",+ "onCompleteParams",+ "onRepeat",+ "onRepeatParams",+ "onReverseComplete",+ "onReverseCompleteParams",+ "parent",+ "onInterrupt",+ "autoRevert",+ "smoothChildTiming",+ ]);+ const registered =+ (window as unknown as { __timelines?: Record<string, Tween> }).__timelines ?? {};+ const names = new Map<Tween, string>();+ for (const [name, timeline] of Object.entries(registered)) {+ if (typeof timeline?.getChildren === "function") names.set(timeline, name);+ }+ const ids = new Map<unknown, number>();++ // A registered timeline nested in another one is walked as part of its parent.+ function nestedInAnother(timeline: Tween): boolean {+ for (let parent = timeline.parent; parent; parent = parent.parent) {+ if (names.has(parent)) return true;+ }+ return false;+ }++ function plainProperties(tween: Tween): string[] {+ const vars = tween.vars ?? {};+ const plain = !vars.repeat && !vars.yoyo && !vars.keyframes && !vars.overwrite;+ return plain ? Object.keys(vars).filter((key) => !NOT_PROPERTIES.has(key)) : [];+ }++ function labelOf(target: unknown): string {+ if (!(target instanceof Element)) return "an object";+ if (target.id) return `#${target.id}`;+ return [target.tagName.toLowerCase(), ...target.classList].join(".");+ }++ function recordsOf(timeline: Tween, name: string): TweenRecord[] {+ const origin = timeline.globalTime(0);+ return (timeline.getChildren?.(true, true, false) ?? []).flatMap((tween) => {+ const duration = tween.totalDuration();+ const properties = plainProperties(tween);+ if (!(duration > 0) || properties.length === 0) return [];+ const start = tween.globalTime(0) - origin;+ const end = tween.globalTime(duration) - origin;+ return tween.targets().map((target) => {+ if (!ids.has(target)) ids.set(target, ids.size);+ const id = ids.get(target) ?? -1;+ return { timeline: name, target: id, label: labelOf(target), properties, start, end };+ });+ });+ }++ return [...names].flatMap(([timeline, name]) =>+ nestedInAnother(timeline) ? [] : recordsOf(timeline, name),+ );+}