Skip to content

πŸŽ₯ Make videos programmatically with React

Address review: drop redundant ticker ticks, rebuild on scope remount, document function-based values and per-frame cost

Fats4031904ce8117c0
diff --git a/packages/docs/docs/gsap/use-gsap-timeline.mdx b/packages/docs/docs/gsap/use-gsap-timeline.mdx
index fb1e06cafa..ff94385199 100644
--- a/packages/docs/docs/gsap/use-gsap-timeline.mdx
+++ b/packages/docs/docs/gsap/use-gsap-timeline.mdx
@@ -119,10 +119,16 @@ Tweens must target DOM or SVG elements. Tweening plain objects animates in the P
The hook rejects `"random(...)"` string values, `stagger: {from: 'random'}` and `repeatRefresh: true` because GSAP resolves them with unseeded `Math.random()`, which differs between render processes. Derive stable values from data or Remotion's [`random()`](/docs/random).
+Function-based values like `y: (index) => index * 20` cannot be inspected. Derive them from the index or other stable inputs, never from `Math.random()` or the current time.
+
### No stray animations
Animations created inside the builder must be attached to the provided timeline. The hook rejects freestanding `gsap.to()` calls and `gsap.delayedCall()`, which advance on the wall clock. A plain zero-duration `gsap.set()` for static state is allowed.
+## Performance
+
+For determinism, every frame renders the timeline forward from time zero instead of stepping incrementally. This is imperceptible for typical timelines; a timeline with many hundreds of tweens pays the cost on every frame.
+
## GSAP plugins
The package does not support GSAP plugins yet. Plugins that depend on user interaction or asynchronous work, like ScrollTrigger and Draggable, are not meaningful in a rendered video.
diff --git a/packages/example/src/Gsap/SamePropertyOverlap.tsx b/packages/example/src/Gsap/SamePropertyOverlap.tsx
index e2e7f982b6..9bbfcee571 100644
--- a/packages/example/src/Gsap/SamePropertyOverlap.tsx
+++ b/packages/example/src/Gsap/SamePropertyOverlap.tsx
@@ -4,11 +4,9 @@ import {AbsoluteFill} from 'remotion';
const SamePropertyOverlapFixture: React.FC = () => {
const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {
- // Two tweens fighting over the same property with overlapping windows:
- // the second tween's start value is recorded lazily at first
- // initialization, which made frame state depend on the frame-visit path
- // before the adapter primed in playback order and rendered forward from
- // zero. This fixture keeps that guarantee honest in the real renderer.
+ // Two tweens contest one property with overlapping windows; lazy
+ // start-value recording makes frames depend on visit order unless the
+ // adapter primes correctly. Keeps that guarantee honest in the renderer.
timeline.to(
selector('[data-contested]'),
{x: 200, duration: 1, ease: 'none'},
diff --git a/packages/gsap/bundle.ts b/packages/gsap/bundle.ts
index 19e7843984..ac3cb0d5b3 100644
--- a/packages/gsap/bundle.ts
+++ b/packages/gsap/bundle.ts
@@ -32,10 +32,8 @@ for (const file of output.outputs) {
await Bun.write(out, str);
}
-// The declarations reference the ambient `gsap` namespace, but tsgo drops
-// triple-slash directives on emit. Without this, consumers who don't import
-// 'gsap' themselves get `any` for every timeline type. The directive resolves
-// through the gsap package's own "types" field.
+// tsgo drops triple-slash directives on emit; without the gsap types
+// reference, consumers who never import 'gsap' get `any` timelines.
const gsapReference = '/// <reference types="gsap" />\n';
for (const declaration of ['dist/index.d.ts', 'dist/use-gsap-timeline.d.ts']) {
const content = await Bun.file(declaration).text();
diff --git a/packages/gsap/src/test/use-gsap-timeline.test.tsx b/packages/gsap/src/test/use-gsap-timeline.test.tsx
index 37d33bf7e5..72a2347575 100644
--- a/packages/gsap/src/test/use-gsap-timeline.test.tsx
+++ b/packages/gsap/src/test/use-gsap-timeline.test.tsx
@@ -14,8 +14,7 @@ import {useGsapTimeline} from '../use-gsap-timeline';
const remotionClock = {frame: 0, fps: 30};
-// Bun patches already-imported ESM modules through live bindings, so this
-// takes effect even though the hook was imported statically above.
+// Bun's mock.module patches already-imported ESM through live bindings.
mock.module('remotion', () => ({
useCurrentFrame: () => remotionClock.frame,
useVideoConfig: () => ({fps: remotionClock.fps}),
@@ -266,10 +265,8 @@ describe('useGsapTimeline', () => {
);
it('rejects timeline-shaping setters with an accurate message', async () => {
- // timeScale(value) and duration(value) dispatch through totalTime()
- // internally; without dedicated guards they threw a misleading
- // "seeking" error. They also cannot be honored, because the hook
- // seeks in unscaled local time.
+ // These route through totalTime() internally and cannot be honored
+ // by unscaled seeks.
const DurationHarness = () => {
const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {
timeline.fromTo(
@@ -305,8 +302,7 @@ describe('useGsapTimeline', () => {
});
it('allows concise builders that return a stray gsap.set tween', async () => {
- // GSAP animations are thenable; the async-builder guard must not
- // mistake them for Promises.
+ // GSAP animations are thenable and must not be mistaken for Promises.
const ConciseSetHarness = () => {
const scope = useGsapTimeline<HTMLDivElement>(({selector}) =>
gsap.set(selector('[data-concise]'), {opacity: 0.75}),
@@ -324,8 +320,8 @@ describe('useGsapTimeline', () => {
});
it('primes nested-timeline sets at their root-time position', async () => {
- // startTime() is parent-relative; a fresh mount landing exactly on a
- // set nested inside an offset child timeline must still render it.
+ // A fresh mount landing exactly on a set nested inside an offset
+ // child timeline must still render it.
const NestedSetHarness = () => {
const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {
timeline.to(selector('[data-nested-set]'), {
@@ -355,6 +351,42 @@ describe('useGsapTimeline', () => {
expect(element.style.backgroundColor).toBe('rgb(9, 8, 7)');
});
+ it('rebuilds the timeline when the scope element remounts', async () => {
+ const RemountHarness = ({show}: {readonly show: boolean}) => {
+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {
+ timeline.fromTo(
+ selector('[data-remount]'),
+ {opacity: 0},
+ {opacity: 1, duration: 1, ease: 'none'},
+ );
+ });
+
+ return show ? (
+ <div ref={scope}>
+ <div data-remount />
+ </div>
+ ) : (
+ <div />
+ );
+ };
+
+ await setFrame(15, <RemountHarness show />);
+ expect(opacity(container.querySelector('[data-remount]')!)).toBeCloseTo(
+ 0.5,
+ 4,
+ );
+
+ // Unmount the scoped root, then bring it back without changing deps.
+ await setFrame(15, <RemountHarness show={false} />);
+ expect(container.querySelector('[data-remount]')).toBeNull();
+
+ await setFrame(15, <RemountHarness show />);
+ expect(opacity(container.querySelector('[data-remount]')!)).toBeCloseTo(
+ 0.5,
+ 4,
+ );
+ });
+
it('rejects asynchronous builders', async () => {
const AsyncHarness = () => {
const scope = useGsapTimeline<HTMLDivElement>(async () => undefined);
@@ -815,11 +847,9 @@ describe('useGsapTimeline', () => {
});
it('keeps guard walks out of GSAP internals and the host React tree', async () => {
- // Staggers inject vars.parent, whose graph reaches tween targets and,
- // through React fiber properties on DOM nodes, the entire host app tree.
- // The surrounding component state deliberately contains prose that the
- // nondeterminism matcher must never see, mirroring the studio preview
- // where chat state holds skill documents mentioning random().
+ // Stagger vars reach tween targets and, via React fibers, the host
+ // tree; the surrounding state holds prose mentioning random() that
+ // the matcher must never see.
const StaggerHarness = () => {
const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {
timeline.fromTo(
diff --git a/packages/gsap/src/use-gsap-timeline.ts b/packages/gsap/src/use-gsap-timeline.ts
index 9917c5dd42..f92e87b4e7 100644
--- a/packages/gsap/src/use-gsap-timeline.ts
+++ b/packages/gsap/src/use-gsap-timeline.ts
@@ -1,6 +1,6 @@
/// <reference types="gsap" />
import {gsap} from 'gsap';
-import {type DependencyList, useLayoutEffect, useRef} from 'react';
+import {type DependencyList, useLayoutEffect, useRef, useState} from 'react';
import {useCurrentFrame, useVideoConfig} from 'remotion';
import {frameToSeconds} from './frame-time';
@@ -49,12 +49,9 @@ const animationVars = (
): Record<string, unknown> =>
(animation as gsap.core.Animation & {vars: Record<string, unknown>}).vars;
-// Vars walks must stay inside author-written configuration. GSAP injects
-// internals into vars (staggers add a `parent` timeline reference), and from
-// there the object graph reaches tween targets β€” DOM nodes whose React fiber
-// properties climb into the entire host application's tree. Recursing only
-// into plain objects and arrays keeps the walk on user data: DOM nodes,
-// Animation instances, and fibers all carry custom prototypes.
+// Recurse only into plain objects and arrays: GSAP injects internals into
+// vars (stagger adds `parent`), whose graph reaches DOM targets and, through
+// their React fibers, the entire host app tree.
const isWalkable = (value: unknown): value is object => {
if (typeof value !== 'object' || value === null) return false;
if (Array.isArray(value)) return true;
@@ -101,8 +98,7 @@ const findTimelineCallbacks = (timeline: gsap.core.Timeline): string[] => {
];
};
-// nodeType instead of instanceof keeps the check correct across realms
-// (renderer processes, jsdom, iframes) where Element identity differs.
+// nodeType, not instanceof: Element identity differs across realms.
const isElementTarget = (target: unknown): boolean =>
typeof target === 'object' &&
target !== null &&
@@ -117,8 +113,7 @@ const describeTarget = (target: unknown): string => {
return typeof target;
}
- // GSAP stamps internal bookkeeping onto tween targets; hide it so the
- // error names the author's own properties.
+ // Hide GSAP's `_gsap` bookkeeping so the error names the author's properties.
const keys = Object.keys(target as object).filter((key) => key !== '_gsap');
const preview = keys.slice(0, 3).join(', ');
return `plain object {${preview}${keys.length > 3 ? ', …' : ''}}`;
@@ -142,13 +137,9 @@ const findNonElementTargets = (timeline: gsap.core.Timeline): string[] => {
return [...new Set(found)];
};
-// GSAP resolves "random(...)" strings with unseeded Math.random at tween
-// initialization, so every mount β€” and every Lambda render chunk β€” rolls
-// different values. Same for random-order staggers. repeatRefresh re-rolls
-// on every repeat cycle, which also re-records lazily on frame revisits.
-// Matches GSAP's random value tokens β€” "random(-100, 100)", "+=random(1,5)",
-// "random([a, b, c])" β€” and not the word "random()" inside prose a
-// composition might legitimately carry.
+// GSAP resolves random value tokens ("random(-100, 100)", "random([a, b])")
+// with unseeded Math.random, so every render chunk rolls different values.
+// Anchored so prose merely containing "random()" does not match.
const GSAP_RANDOM_TOKEN = /random\(\s*(-?[\d.]|\[)/;
const findNondeterministicVars = (
@@ -199,11 +190,9 @@ const findTimelineNondeterminism = (timeline: gsap.core.Timeline): string[] => {
];
};
-// Animations created inside the builder but never parented under the package
-// timeline live on gsap.globalTimeline and advance on the wall clock β€” a
-// second, nondeterministic frame source the timeline walk cannot see. Static
-// zero-duration, callback-free, delay-free tweens (the gsap.set pattern) are
-// deterministic at build time and stay allowed.
+// Builder-created animations that never join the timeline advance on the
+// wall clock. Zero-duration, callback-free, delay-free tweens (gsap.set)
+// are deterministic at build time and stay allowed.
const findStrayAnimations = (
timeline: gsap.core.Timeline,
preexisting: Set<gsap.core.Animation>,
@@ -252,9 +241,8 @@ type TimelineControls = {
const guardTimelineMethods = (
timeline: gsap.core.Timeline,
): TimelineControls => {
- // Bind the package-owned controls before replacing the public methods the
- // builder receives. Internal frame seeking and cleanup must remain possible
- // without giving user code a second clock.
+ // Bind originals first: the hook must keep seeking and cleaning up after
+ // the guards replace the public methods.
const originalPaused = timeline.paused.bind(timeline);
const originalTotalTime = timeline.totalTime.bind(timeline);
const originalKill = timeline.kill.bind(timeline);
@@ -295,13 +283,9 @@ const guardTimelineMethods = (
);
};
- // timeScale(value), duration(value) and totalDuration(value) dispatch
- // through the public totalTime() internally, so without explicit guards
- // they would trip the seeking error with a misleading message. They also
- // cannot be honored: the hook seeks in unscaled local time, so a changed
- // time scale would silently desynchronize the video from GSAP's own
- // playback. Reject the setters with an accurate message; the zero-argument
- // getters stay available (the hook itself reads duration()).
+ // These setters dispatch through totalTime() internally and cannot be
+ // honored anyway (the hook seeks unscaled local time), so reject them
+ // with an accurate message. The zero-argument getters stay available.
for (const method of ['timeScale', 'duration', 'totalDuration'] as const) {
const original = (timeline[method] as (...args: unknown[]) => unknown).bind(
timeline,
@@ -397,19 +381,15 @@ const guardTimelineMethods = (
originalPaused(true);
},
renderAt: (seconds) => {
- // Always render forward from zero. GSAP renders timeline children in
- // reverse order on backward passes, so overlapping same-property
- // tweens resolve differently when a frame is approached from above
- // vs below. Two forward passes make every visit β€” direct still,
- // sequential chunk, backward scrub β€” identical to forward playback.
+ // Render forward from zero: GSAP renders children in reverse order on
+ // backward passes, so overlapping same-property tweens resolve
+ // differently unless every visit replays forward playback.
originalTotalTime(0, true);
originalTotalTime(seconds, true);
},
restoreForContextRevert: () => {
- // gsap.context().revert() calls animation.kill(), which in turn reaches
- // public progress/time methods. Remove every instance-level guard only
- // after builder execution is permanently over so GSAP teardown can use
- // its untouched prototype implementation.
+ // context.revert() reaches public progress/time methods via kill();
+ // restore the prototypes once builder execution is permanently over.
for (const method of [
'play',
'resume',
@@ -458,9 +438,14 @@ export const useGsapTimeline = <T extends Element>(
const {fps} = useVideoConfig();
const scopeRef = useRef<T>(null);
const controlsRef = useRef<TimelineControls | null>(null);
+ // Element the current timeline was built for. A conditionally unmounted
+ // scope runs no cleanup, leaving a stale timeline on the detached element.
+ const builtForRef = useRef<Element | null>(null);
const buildRef = useRef(build);
const frameRef = useRef(frame);
const fpsRef = useRef(fps);
+ // Bumped to re-run the build effect when the scope element changes.
+ const [remountNonce, setRemountNonce] = useState(0);
buildRef.current = build;
frameRef.current = frame;
@@ -468,6 +453,7 @@ export const useGsapTimeline = <T extends Element>(
useLayoutEffect(() => {
const scope = scopeRef.current;
+ builtForRef.current = scope;
if (!scope) {
return;
}
@@ -511,9 +497,7 @@ export const useGsapTimeline = <T extends Element>(
);
}
- // Only reject genuine Promises. GSAP animations are thenable, so a
- // duck-typed check would reject concise builders that return a
- // tween, like `({selector}) => gsap.set(selector('[data-x]'), ...)`.
+ // GSAP animations are thenable; only a genuine Promise means async.
if (result instanceof Promise) {
throw new TypeError(
'useGsapTimeline builders must be synchronous. Load data before building the timeline.',
@@ -557,21 +541,12 @@ export const useGsapTimeline = <T extends Element>(
// Builders only describe motion. Reassert package ownership of playback.
state.controls.pause();
- // A freshly built timeline is not yet path-independent: zero-duration
- // tweens exactly at the playhead do not render until passed, and
- // overlapping same-property tweens lazily record their start values
- // at whatever frame happens to be visited first β€” so a direct still
- // could differ from the same frame reached sequentially (concurrent
- // render chunks make both orders happen in one video). Prime the
- // timeline by sweeping the playhead through every child's start time
- // in playback order, flushing GSAP's lazy value-recording after each
- // step, so initialization happens exactly as sequential playback
- // would do it. Runs synchronously inside this layout effect, so no
- // intermediate state paints. Infinite repeats keep start times
- // finite, so the sweep stays finite too.
- // startTime() is relative to the child's immediate parent; walk up
- // to express it on the owned timeline's clock (a nested timeline's
- // timeScale stretches its children's local time).
+ // A fresh timeline is not path-independent: zero-duration tweens at
+ // the playhead render only once passed, and overlapping tweens
+ // record start values lazily at the first visited frame. Sweep the
+ // playhead through every child start time in playback order so
+ // initialization matches sequential playback. startTime() is
+ // parent-relative, so map it onto this timeline's clock.
const ownedTimeline = state.timeline;
const startTimeOnOwnedClock = (child: gsap.core.Animation): number => {
let time = child.startTime();
@@ -602,13 +577,11 @@ export const useGsapTimeline = <T extends Element>(
: 3600;
for (const startTime of [...startTimes, primeEnd]) {
state.controls.renderAt(startTime);
- gsap.ticker.tick();
}
state.controls.renderAt(
frameToSeconds(frameRef.current, fpsRef.current),
);
- gsap.ticker.tick();
});
controlsRef.current = state.controls;
@@ -627,7 +600,7 @@ export const useGsapTimeline = <T extends Element>(
};
// The explicit dependency list is the same contract as useEffect dependencies.
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, dependencies);
+ }, [...dependencies, remountNonce]);
useLayoutEffect(() => {
const controls = controlsRef.current;
@@ -636,5 +609,15 @@ export const useGsapTimeline = <T extends Element>(
}
}, [fps, frame]);
+ // Runs every commit: re-arm the build effect if the scope element is not
+ // the one the timeline was built for. Identities match after the rebuild,
+ // so the update chain is finite.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ useLayoutEffect(() => {
+ if (scopeRef.current !== builtForRef.current) {
+ setRemountNonce((nonce) => nonce + 1);
+ }
+ });
+
return scopeRef;
};