π₯ Make videos programmatically with React
`@remotion/gsap`: Add package for deterministic GSAP timelines
Fats403800571d63a81
diff --git a/bun.lock b/bun.lockindex c8b74ff0f5..bb32950400 100644--- a/bun.lock+++ b/bun.lock@@ -522,6 +522,7 @@"@remotion/fonts": "workspace:*","@remotion/gif": "workspace:*","@remotion/google-fonts": "workspace:*",+ "@remotion/gsap": "workspace:*","@remotion/install-whisper-cpp": "workspace:*","@remotion/lambda": "workspace:*","@remotion/lambda-client": "workspace:*",@@ -579,6 +580,7 @@"crawlchat-client": "1.2.1","create-video": "workspace:*","eslint": "catalog:",+ "gsap": "3.15.0","hls.js": "0.14.17","https-proxy-agent": "7.0.6","lottie-web": "5.13.0",@@ -771,6 +773,7 @@"@remotion/fonts": "workspace:*","@remotion/gif": "workspace:*","@remotion/google-fonts": "workspace:*",+ "@remotion/gsap": "workspace:*","@remotion/lambda": "workspace:*","@remotion/lambda-client": "workspace:*","@remotion/layout-utils": "workspace:*",@@ -815,6 +818,7 @@"babel-loader": "8.2.2","css-loader": "7.1.4","dotenv": "17.3.1",+ "gsap": "3.15.0","hls.js": "0.14.17","lottie-web": "5.13.0","mediabunny": "catalog:",@@ -908,6 +912,29 @@"postcss": "8.5.23",},},+ "packages/gsap": {+ "name": "@remotion/gsap",+ "version": "4.0.515",+ "dependencies": {+ "remotion": "workspace:*",+ },+ "devDependencies": {+ "@happy-dom/global-registrator": "14.5.1",+ "@remotion/eslint-config-internal": "workspace:*",+ "@types/react": "catalog:",+ "@types/react-dom": "catalog:",+ "@typescript/native-preview": "catalog:",+ "eslint": "catalog:",+ "gsap": "3.15.0",+ "react": "catalog:",+ "react-dom": "catalog:",+ },+ "peerDependencies": {+ "gsap": ">=3.12.0 <4",+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0",+ },+ },"packages/install-whisper-cpp": {"name": "@remotion/install-whisper-cpp","version": "4.0.515",@@ -961,9 +988,12 @@"@remotion/zod-types": "workspace:*","@rspack/core": "1.7.11","@types/node": "catalog:",+ "@types/pngjs": "6.0.5","@types/sharp": "0.28.6","create-video": "workspace:*","execa": "5.1.1",+ "pixelmatch": "7.1.0",+ "pngjs": "7.0.0","postcss": "8.5.23","postcss-loader": "7.3.4","postcss-size": "5.0.0",@@ -4357,6 +4387,8 @@"@remotion/google-fonts": ["@remotion/google-fonts@workspace:packages/google-fonts"],+ "@remotion/gsap": ["@remotion/gsap@workspace:packages/gsap"],+"@remotion/install-whisper-cpp": ["@remotion/install-whisper-cpp@workspace:packages/install-whisper-cpp"],"@remotion/it-tests": ["@remotion/it-tests@workspace:packages/it-tests"],@@ -5273,6 +5305,8 @@"@types/opentype.js": ["@types/[email protected]", "", {}, "sha512-6fbXi67I07ugNM+FExwJnfuui2hD7hraD6nqjr3UnqsbBpxSkrtmO6tBubPdNAjqRT9TVkquVkNS9IkgTtq6/w=="],+ "@types/pngjs": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ=="],+"@types/prettier": ["@types/[email protected]", "", {}, "sha512-KufADq8uQqo1pYKVIYzfKbJfBAc0sOeXqGbFaSpv8MRmC/zXgowNZmFcbngndGk922QDmOASEXUZCaY48gs4cg=="],"@types/prismjs": ["@types/[email protected]", "", {}, "sha512-rlAnzkW2sZOjbqZ743IHUhFcvzaGbqijwOu8QZnZCjfQzBqFE3s4lOTJEsxikImav9uzz/42I+O7YUs1mWgMlg=="],@@ -6563,6 +6597,8 @@"gray-matter": ["[email protected]", "", { "dependencies": { "js-yaml": "3.14.1", "kind-of": "6.0.3", "section-matter": "1.0.0", "strip-bom-string": "1.0.0" } }, "sha512-5v6yZd4JK3eMI3FqqCouswVqwugaA9r4dNZB1wwcmrD02QkV5H0y7XBQW8QwQqEaZY1pM9aqORSORhJRdNK44Q=="],+ "gsap": ["[email protected]", "", {}, "sha512-dMW4CWBTUK1AEEDeZc1g4xpPGIrSf9fJF960qbTZmN/QwZIWY5wgliS6JWl9/25fpTGJrMRtSjGtOmPnfjZB+A=="],+"gtoken": ["[email protected]", "", { "dependencies": { "gaxios": "5.1.0", "google-p12-pem": "4.0.1", "jws": "4.0.0" } }, "sha512-4ccGpzz7YAr7lxrT2neugmXQ3hP9ho2gcaityLVkiUecAiwiy60Ii8gRbZeOsXV19fYaRjgBSshs8kXw+NKCPQ=="],"gunzip-maybe": ["[email protected]", "", { "dependencies": { "browserify-zlib": "0.1.4", "is-deflate": "1.0.0", "is-gzip": "1.0.0", "peek-stream": "1.1.3", "pumpify": "1.5.1", "through2": "2.0.5" }, "bin": { "gunzip-maybe": "bin.js" } }, "sha512-4haO1M4mLO91PW57BMsDFf75UmwoRX0GkdD+Faw+Lr+r/OZrOCS0pIBwOL1xCKQqnQzbNFGgK2V2CpBUPeFNTw=="],@@ -10435,6 +10471,10 @@"@remotion/gif/react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.3" } }, "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg=="],+ "@remotion/gsap/react": ["[email protected]", "", {}, "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA=="],++ "@remotion/gsap/react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.3" } }, "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg=="],+"@remotion/lambda/@types/express": ["@types/[email protected]", "", { "dependencies": { "@types/body-parser": "1.19.1", "@types/express-serve-static-core": "5.0.4", "@types/serve-static": "1.13.10" } }, "sha512-UZUw8vjpWFXuDnjFTh7/5c2TWDlQqeXHi6hcN7F2XSVT5P+WmUnnbFS3KA6Jnc6IsEqI2qCVu2bK0R0J4A8ZQQ=="],"@remotion/lambda-client/@types/express": ["@types/[email protected]", "", { "dependencies": { "@types/body-parser": "1.19.1", "@types/express-serve-static-core": "5.0.4", "@types/serve-static": "1.13.10" } }, "sha512-UZUw8vjpWFXuDnjFTh7/5c2TWDlQqeXHi6hcN7F2XSVT5P+WmUnnbFS3KA6Jnc6IsEqI2qCVu2bK0R0J4A8ZQQ=="],@@ -11033,6 +11073,8 @@"@types/nlcst/@types/unist": ["@types/[email protected]", "", {}, "sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ=="],+ "@types/pngjs/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-GYDxsZi3ChgmckRT9HPU0WEhKLP08ev/Yfcq2AstjrDASOYCSXeyjDsHg4v5t4jOj7cyDX3vmprafKlWIG9MXQ=="],+"@types/react-native/@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "3.1.3" } }, "sha512-MY3oPudxvMYyesqs/kW1Bh8y9VqSmf+tzqw3ae8a9DZW68pUe3zAdHeI1jc6iAysuRdACnVknHP8AhwD4/dxtg=="],"@types/react-router/@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "3.1.3" } }, "sha512-MY3oPudxvMYyesqs/kW1Bh8y9VqSmf+tzqw3ae8a9DZW68pUe3zAdHeI1jc6iAysuRdACnVknHP8AhwD4/dxtg=="],@@ -16277,6 +16319,8 @@"@types/mute-stream/@types/node/undici-types": ["[email protected]", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],+ "@types/pngjs/@types/node/undici-types": ["[email protected]", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],+"@types/react-native/@types/react/csstype": ["[email protected]", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="],"@types/react-router-config/@types/react/csstype": ["[email protected]", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="],diff --git a/packages/STATS.md b/packages/STATS.mdindex 432061fa9a..e47e6b191f 100644--- a/packages/STATS.md+++ b/packages/STATS.md@@ -29,6 +29,7 @@ Monthly downloads of Remotion packages[](https://npmcharts.com/compare/@remotion/fonts?minimal=true)[](https://npmcharts.com/compare/@remotion/gif?minimal=true)[](https://npmcharts.com/compare/@remotion/google-fonts?minimal=true)+[](https://npmcharts.com/compare/@remotion/gsap?minimal=true)[](https://npmcharts.com/compare/@remotion/install-whisper-cpp?minimal=true)[](https://npmcharts.com/compare/@remotion/lambda?minimal=true)[](https://npmcharts.com/compare/@remotion/layout-utils?minimal=true)diff --git a/packages/cli/src/list-of-remotion-packages.ts b/packages/cli/src/list-of-remotion-packages.tsindex d119e90efd..f5e271b3da 100644--- a/packages/cli/src/list-of-remotion-packages.ts+++ b/packages/cli/src/list-of-remotion-packages.ts@@ -36,6 +36,7 @@ export const listOfRemotionPackages = ['@remotion/fonts','@remotion/gif','@remotion/google-fonts',+ '@remotion/gsap','@remotion/install-whisper-cpp','@remotion/it-tests','@remotion/react18-tests',diff --git a/packages/create-video/src/list-of-remotion-packages.ts b/packages/create-video/src/list-of-remotion-packages.tsindex d119e90efd..f5e271b3da 100644--- a/packages/create-video/src/list-of-remotion-packages.ts+++ b/packages/create-video/src/list-of-remotion-packages.ts@@ -36,6 +36,7 @@ export const listOfRemotionPackages = ['@remotion/fonts','@remotion/gif','@remotion/google-fonts',+ '@remotion/gsap','@remotion/install-whisper-cpp','@remotion/it-tests','@remotion/react18-tests',diff --git a/packages/docs/components/TableOfContents/api.tsx b/packages/docs/components/TableOfContents/api.tsxindex dd6f95c5d1..d9d5d79847 100644--- a/packages/docs/components/TableOfContents/api.tsx+++ b/packages/docs/components/TableOfContents/api.tsx@@ -9,6 +9,7 @@ import {TableOfContents as EnableScssTableOfContents} from '../../docs/enable-scimport {TableOfContents as FontsTableOfContents} from '../../docs/fonts-api/TableOfContents';import {TableOfContents as GifTableOfContents} from '../../docs/gif/table-of-contents';import {TableOfContents as GoogleFontsTableOfContents} from '../../docs/google-fonts/TableOfContents';+import {TableOfContents as GsapTableOfContents} from '../../docs/gsap/table-of-contents';import {TableOfContents as InstallWhisperCppTableOfContents} from '../../docs/install-whisper-cpp/install-whisper-cpp';import {TableOfContents as LambdaTableOfContents} from '../../docs/lambda/table-of-contents';import {TableOfContents as LayoutUtilsTableOfContents} from '../../docs/layout-utils/table-of-contents';@@ -98,6 +99,9 @@ export const TableOfContents: React.FC = () => {<h2>@remotion/google-fonts</h2><p>Load Google Fonts onto a page.</p><GoogleFontsTableOfContents />+ <h2>@remotion/gsap</h2>+ <p>Drive GSAP timelines from the Remotion frame.</p>+ <GsapTableOfContents /><h2>@remotion/install-whisper-cpp</h2><p>Whisper.cpp installation and transcription</p><InstallWhisperCppTableOfContents />diff --git a/packages/docs/docs/gsap/index.mdx b/packages/docs/docs/gsap/index.mdxnew file mode 100644index 0000000000..7cafd86dea--- /dev/null+++ b/packages/docs/docs/gsap/index.mdx@@ -0,0 +1,29 @@+---+image: /generated/articles-docs-gsap-index.png+id: gsap-index+sidebar_label: Overview+title: '@remotion/gsap'+slug: /gsap+---++# @remotion/gsap<AvailableFrom v="4.0.516" />++import {TableOfContents} from './table-of-contents';++Use [GSAP](https://gsap.com/) timelines in Remotion.++GSAP normally advances animations on its own ticker, which runs on the wall clock. Remotion requires every frame to be a pure function of [`useCurrentFrame()`](/docs/use-current-frame). This package builds a paused GSAP timeline and seeks it to the current frame, so previews, scrubbing and renders are deterministic.++<Installation pkg="@remotion/gsap" />++Also install `gsap` itself, which is a peer dependency:++<Installation pkg="gsap" />++## APIs++<TableOfContents />++## License++MITdiff --git a/packages/docs/docs/gsap/table-of-contents.tsx b/packages/docs/docs/gsap/table-of-contents.tsxnew file mode 100644index 0000000000..5f652d7e98--- /dev/null+++ b/packages/docs/docs/gsap/table-of-contents.tsx@@ -0,0 +1,18 @@+import React from 'react';+import {Grid} from '../../components/TableOfContents/Grid';+import {TOCItem} from '../../components/TableOfContents/TOCItem';++export const TableOfContents: React.FC = () => {+ return (+ <div>+ <Grid>+ <TOCItem link="/docs/gsap/use-gsap-timeline">+ <strong>+ <code>useGsapTimeline()</code>+ </strong>+ <div>Build a GSAP timeline that is driven by the Remotion frame</div>+ </TOCItem>+ </Grid>+ </div>+ );+};diff --git a/packages/docs/docs/gsap/use-gsap-timeline.mdx b/packages/docs/docs/gsap/use-gsap-timeline.mdxnew file mode 100644index 0000000000..fb1e06cafa--- /dev/null+++ b/packages/docs/docs/gsap/use-gsap-timeline.mdx@@ -0,0 +1,138 @@+---+image: /generated/articles-docs-gsap-use-gsap-timeline.png+id: use-gsap-timeline+title: useGsapTimeline()+crumb: '@remotion/gsap'+---++# useGsapTimeline()<AvailableFrom v="4.0.516" />++_Part of the [`@remotion/gsap`](/docs/gsap) package._++Builds a scoped, paused GSAP timeline and seeks it to the current frame of the Remotion timeline.++The timeline never plays on GSAP's ticker. On every frame, the hook positions the timeline at `frame / fps`. The same frame produces the same pixels in the [`<Player>`](/docs/player/player), in the Studio, and in stills and concurrent renders.++## Example++```tsx twoslash title="MyComposition.tsx"+import {useGsapTimeline} from '@remotion/gsap';+import React from 'react';+import {AbsoluteFill} from 'remotion';++export const MyComposition: React.FC = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline+ .from(selector('[data-title]'), {+ y: 40,+ opacity: 0,+ duration: 0.8,+ ease: 'power3.out',+ })+ .to(selector('[data-badge]'), {+ rotation: 360,+ duration: 2,+ ease: 'none',+ });+ });++ return (+ <AbsoluteFill ref={scope} style={{background: '#000', color: '#fff'}}>+ <h1 data-title>Hello GSAP</h1>+ <div data-badge style={{width: 60, height: 60, background: '#B8FF5A'}} />+ </AbsoluteFill>+ );+};+```++Attach the returned ref to the element that contains everything the timeline animates. Use the scoped `selector()` to target descendants. Matches never leak into other components, even if the same attribute is used elsewhere.++## API++### `build`++A synchronous function that receives a build context and adds tweens to the timeline. It runs once on mount and again whenever [`dependencies`](#dependencies) change.++#### `timeline`++A `gsap.core.Timeline` that is owned by the hook and already paused at time zero. Add tweens using the regular GSAP API: `to()`, `from()`, `fromTo()`, `set()`, `add()`, labels, position parameters, staggers, keyframes, repeats, yoyo and nested timelines all work.++#### `scope`++The mounted element attached to the returned ref.++#### `selector`++A GSAP selector function restricted to descendants of `scope`.++### `options?`++#### `dependencies?`++An array of values, like the dependency list of `useEffect()`. When one of them changes, the hook reverts the previous timeline and runs the builder again. Default: the timeline is built once per mount.++```tsx twoslash title="Rebuilding on prop changes"+import {useGsapTimeline} from '@remotion/gsap';+import React from 'react';++export const Title: React.FC<{distance: number}> = ({distance}) => {+ const scope = useGsapTimeline<HTMLDivElement>(+ ({timeline, selector}) => {+ timeline.to(selector('[data-box]'), {x: distance, duration: 1});+ },+ {dependencies: [distance]},+ );++ return (+ <div ref={scope}>+ <div data-box />+ </div>+ );+};+```++## Return value++A ref object. Attach it to the HTML or SVG element that scopes the timeline.++## Rules for builders++The hook rejects patterns that would break deterministic rendering. Each of these throws an error during the build:++### No playback or seeking++The hook blocks `play()`, `resume()`, `restart()`, `reverse()`, `paused(false)`, `seek()`, `time()`, `progress()`, `tweenTo()` and similar methods. Remotion owns the clock; the hook performs all seeking.++### No callbacks++The hook rejects `onStart`, `onUpdate`, `onComplete` and other callbacks, as well as `timeline.call()`, `timeline.eventCallback()` and `timeline.then()`. A render may visit frames in any order and split them across multiple browser instances, so callbacks would not fire in a meaningful sequence. Derive state from the timeline instead.++### Synchronous builders only++Builders must not return a Promise. Load data before rendering, for example with [`delayRender()`](/docs/delay-render) or [`calculateMetadata()`](/docs/calculate-metadata).++### Only element targets++Tweens must target DOM or SVG elements. Tweening plain objects animates in the Player but freezes in stills and renders, because nothing re-reads the object after a frame seek. Derive numeric values with [`useCurrentFrame()`](/docs/use-current-frame) and [`interpolate()`](/docs/interpolate) instead.++### No unseeded randomness++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).++### 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.++## 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.++## Compatibility++<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering serverSideRendering player studio hideServers />++## See also++- [Source code for this hook](https://github.com/remotion-dev/remotion/blob/main/packages/gsap/src/use-gsap-timeline.ts)+- [`@remotion/gsap`](/docs/gsap)+- [Third party integrations](/docs/third-party)diff --git a/packages/docs/docs/resources.mdx b/packages/docs/docs/resources.mdxindex b22f09353e..568d936975 100644--- a/packages/docs/docs/resources.mdx+++ b/packages/docs/docs/resources.mdx@@ -141,7 +141,7 @@ See the [Showcase](/showcase) for videos made with Remotion.- [Fireship: Remotion Tutorial](https://www.youtube.com/watch?v=deg8bOoziaE&t=3s)- [CRT effect](https://www.youtube.com/watch?v=-7MOoWN2_nk)- ["Create videos with Code" by Prismic](https://prismic.io/blog/create-videos-with-code-remotion-tutorial)-- [Integrate GreenSock with Remotion](https://archive.ph/dGQ19)+- [Use GSAP timelines in Remotion](/docs/gsap)- [DVD Screensaver Tutorial](https://www.youtube.com/watch?v=n69siyttEwM)- [Remotion Tutorial by Alfonso Graziano](https://www.youtube.com/watch?v=r4v1J7ozxIg)- [Timing animations](https://www.youtube.com/watch?v=WigIALCnEvw)diff --git a/packages/docs/docs/third-party.mdx b/packages/docs/docs/third-party.mdxindex 7eea88ee5d..7fe67f3b71 100644--- a/packages/docs/docs/third-party.mdx+++ b/packages/docs/docs/third-party.mdx@@ -34,9 +34,9 @@ At the moment, we don't have a Framer Motion integration, but are discussing theUse the [`@remotion/gif`](/docs/gif) package.-## GreenSock+## GSAP (GreenSock) {#greensock}-See: [How to integrate GreenSock with Remotion](https://archive.ph/dGQ19)+Use the [`@remotion/gsap`](/docs/gsap) package.## Lottiediff --git a/packages/docs/package.json b/packages/docs/package.jsonindex 99ec0824e1..05a354c33c 100644--- a/packages/docs/package.json+++ b/packages/docs/package.json@@ -60,6 +60,7 @@"@remotion/fonts": "workspace:*","@remotion/gif": "workspace:*","@remotion/google-fonts": "workspace:*",+ "@remotion/gsap": "workspace:*","@remotion/install-whisper-cpp": "workspace:*","@remotion/lambda": "workspace:*","@remotion/lambda-client": "workspace:*",@@ -116,6 +117,7 @@"crawlchat-client": "1.2.1","create-video": "workspace:*","eslint": "catalog:",+ "gsap": "3.15.0","hls.js": "0.14.17","https-proxy-agent": "7.0.6","lottie-web": "5.13.0",diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex 8c542321a0..3cdecb499e 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -397,6 +397,15 @@ const sidebars: SidebarsConfig = {'google-fonts/load-font-from-info',],},+ {+ type: 'category',+ label: '@remotion/gsap',+ link: {+ type: 'doc',+ id: 'gsap/gsap-index',+ },+ items: ['gsap/use-gsap-timeline'],+ },{type: 'category',label: '@remotion/install-whisper-cpp',diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex cf8be751e9..e6658362bc 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -2807,6 +2807,24 @@ export const articles = [noAi: false,slug: 'greenscreen',},+ {+ id: 'gsap-index',+ title: '@remotion/gsap',+ relativePath: 'docs/gsap/index.mdx',+ compId: 'articles-docs-gsap-index',+ crumb: null,+ noAi: false,+ slug: 'gsap',+ },+ {+ id: 'use-gsap-timeline',+ title: 'useGsapTimeline()',+ relativePath: 'docs/gsap/use-gsap-timeline.mdx',+ compId: 'articles-docs-gsap-use-gsap-timeline',+ crumb: '@remotion/gsap',+ noAi: false,+ slug: 'gsap/use-gsap-timeline',+ },{id: 'hardware-acceleration',title: 'Hardware accelerated encoding',diff --git a/packages/docs/static/generated/articles-docs-gsap-index.png b/packages/docs/static/generated/articles-docs-gsap-index.pngnew file mode 100644index 0000000000..b13cb17354Binary files /dev/null and b/packages/docs/static/generated/articles-docs-gsap-index.png differdiff --git a/packages/docs/static/generated/articles-docs-gsap-use-gsap-timeline.png b/packages/docs/static/generated/articles-docs-gsap-use-gsap-timeline.pngnew file mode 100644index 0000000000..1f9443fa1aBinary files /dev/null and b/packages/docs/static/generated/articles-docs-gsap-use-gsap-timeline.png differdiff --git a/packages/example/package.json b/packages/example/package.jsonindex 29313a812a..667af0f6c8 100644--- a/packages/example/package.json+++ b/packages/example/package.json@@ -52,6 +52,7 @@"@remotion/fonts": "workspace:*","@remotion/gif": "workspace:*","@remotion/google-fonts": "workspace:*",+ "@remotion/gsap": "workspace:*","@remotion/lambda": "workspace:*","@remotion/lambda-client": "workspace:*","@remotion/layout-utils": "workspace:*",@@ -95,6 +96,7 @@"babel-loader": "8.2.2","css-loader": "7.1.4","dotenv": "17.3.1",+ "gsap": "3.15.0","hls.js": "0.14.17","lottie-web": "5.13.0","mediabunny": "catalog:",diff --git a/packages/example/src/Gsap/NestedSequence.tsx b/packages/example/src/Gsap/NestedSequence.tsxnew file mode 100644index 0000000000..4e9708bfc4--- /dev/null+++ b/packages/example/src/Gsap/NestedSequence.tsx@@ -0,0 +1,15 @@+import React from 'react';+import {AbsoluteFill, Sequence} from 'remotion';+import {OpacityFixture} from './OpacityFixture';++const NestedSequenceFixture: React.FC = () => (+ <AbsoluteFill style={{background: '#000'}}>+ <Sequence from={20} durationInFrames={60} premountFor={10}>+ <Sequence from={10} durationInFrames={45} premountFor={5}>+ <OpacityFixture />+ </Sequence>+ </Sequence>+ </AbsoluteFill>+);++export default NestedSequenceFixture;diff --git a/packages/example/src/Gsap/OpacityFixture.tsx b/packages/example/src/Gsap/OpacityFixture.tsxnew file mode 100644index 0000000000..a074ecfc6d--- /dev/null+++ b/packages/example/src/Gsap/OpacityFixture.tsx@@ -0,0 +1,21 @@+import {useGsapTimeline} from '@remotion/gsap';+import React from 'react';+import {AbsoluteFill} from 'remotion';++export const OpacityFixture: React.FC = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.fromTo(+ selector('[data-red]'),+ {opacity: 0},+ {opacity: 1, duration: 1, ease: 'none'},+ );+ });++ return (+ <AbsoluteFill ref={scope} style={{background: '#000'}}>+ <AbsoluteFill data-red style={{background: '#f00'}} />+ </AbsoluteFill>+ );+};++export default OpacityFixture;diff --git a/packages/example/src/Gsap/Overlap.tsx b/packages/example/src/Gsap/Overlap.tsxnew file mode 100644index 0000000000..e10ecbe644--- /dev/null+++ b/packages/example/src/Gsap/Overlap.tsx@@ -0,0 +1,47 @@+import {useGsapTimeline} from '@remotion/gsap';+import React from 'react';+import {AbsoluteFill, Sequence} from 'remotion';++const OverlapLayer: React.FC<{color: string; direction: number}> = ({+ color,+ direction,+}) => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.fromTo(+ selector('[data-layer]'),+ {x: direction * 130, opacity: 0, scale: 0.6},+ {x: 0, opacity: 0.82, scale: 1, duration: 1, ease: 'power3.out'},+ );+ });++ return (+ <AbsoluteFill+ ref={scope}+ style={{alignItems: 'center', justifyContent: 'center'}}+ >+ <div+ data-layer+ style={{+ width: 150,+ height: 90,+ borderRadius: 28,+ background: color,+ mixBlendMode: 'screen',+ }}+ />+ </AbsoluteFill>+ );+};++const OverlapFixture: React.FC = () => (+ <AbsoluteFill style={{background: '#05060B'}}>+ <Sequence from={10} durationInFrames={55} premountFor={10}>+ <OverlapLayer color="#7C5CFF" direction={-1} />+ </Sequence>+ <Sequence from={30} durationInFrames={55} premountFor={10}>+ <OverlapLayer color="#FF5F8F" direction={1} />+ </Sequence>+ </AbsoluteFill>+);++export default OverlapFixture;diff --git a/packages/example/src/Gsap/SamePropertyOverlap.tsx b/packages/example/src/Gsap/SamePropertyOverlap.tsxnew file mode 100644index 0000000000..e2e7f982b6--- /dev/null+++ b/packages/example/src/Gsap/SamePropertyOverlap.tsx@@ -0,0 +1,39 @@+import {useGsapTimeline} from '@remotion/gsap';+import React from 'react';+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.+ timeline.to(+ selector('[data-contested]'),+ {x: 200, duration: 1, ease: 'none'},+ 0,+ );+ timeline.to(+ selector('[data-contested]'),+ {x: 0, duration: 1, ease: 'none'},+ 0.5,+ );+ });++ return (+ <AbsoluteFill ref={scope} style={{background: '#05060B'}}>+ <div+ data-contested+ style={{+ width: 60,+ height: 60,+ borderRadius: 12,+ background: '#B8FF5A',+ }}+ />+ </AbsoluteFill>+ );+};++export default SamePropertyOverlapFixture;diff --git a/packages/example/src/Gsap/Sequence.tsx b/packages/example/src/Gsap/Sequence.tsxnew file mode 100644index 0000000000..7be452e508--- /dev/null+++ b/packages/example/src/Gsap/Sequence.tsx@@ -0,0 +1,13 @@+import React from 'react';+import {AbsoluteFill, Sequence} from 'remotion';+import {OpacityFixture} from './OpacityFixture';++const SequenceFixture: React.FC = () => (+ <AbsoluteFill style={{background: '#000'}}>+ <Sequence from={30} durationInFrames={45} premountFor={10}>+ <OpacityFixture />+ </Sequence>+ </AbsoluteFill>+);++export default SequenceFixture;diff --git a/packages/example/src/Gsap/Showcase.tsx b/packages/example/src/Gsap/Showcase.tsxnew file mode 100644index 0000000000..b161c13236--- /dev/null+++ b/packages/example/src/Gsap/Showcase.tsx@@ -0,0 +1,315 @@+import {useGsapTimeline} from '@remotion/gsap';+import React from 'react';+import {AbsoluteFill} from 'remotion';++const cards = [+ {number: '01', label: 'Frame locked', color: '#B8FF5A'},+ {number: '02', label: 'Random access', color: '#7C5CFF'},+ {number: '03', label: 'Nested rhythm', color: '#FF5F8F'},+];++const title = ['TIMELINES', 'MEET', 'REMOTION'];++const GsapShowcase: React.FC = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ const titleWords = selector('[data-title-word]');+ const cardElements = selector('[data-card]');+ const metrics = selector('[data-metric]');++ timeline+ .set(selector('[data-stage]'), {opacity: 1})+ .from(selector('[data-kicker]'), {+ y: 24,+ opacity: 0,+ letterSpacing: '0.7em',+ duration: 0.65,+ ease: 'power3.out',+ })+ .from(+ titleWords,+ {+ yPercent: 130,+ rotateX: -70,+ opacity: 0,+ transformOrigin: '50% 100%',+ duration: 0.9,+ stagger: 0.1,+ ease: 'power4.out',+ },+ 0.18,+ )+ .from(+ selector('[data-rule]'),+ {scaleX: 0, duration: 1.1, transformOrigin: '0% 50%', ease: 'expo.out'},+ 0.42,+ )+ .from(+ cardElements,+ {+ y: 150,+ scale: 0.68,+ rotate: (index: number) => (index - 1) * 9,+ opacity: 0,+ duration: 1,+ stagger: {each: 0.13, from: 'center'},+ ease: 'back.out(1.45)',+ },+ 0.92,+ )+ .to(+ selector('[data-orbit]'),+ {rotation: 360, duration: 5.4, ease: 'none'},+ 0,+ )+ .to(+ selector('[data-glow]'),+ {x: 680, y: -160, scale: 1.65, duration: 4.5, ease: 'sine.inOut'},+ 0,+ )+ .addLabel('metrics', 2)+ .from(+ metrics,+ {y: 28, opacity: 0, duration: 0.55, stagger: 0.08, ease: 'power3.out'},+ 'metrics',+ )+ .to(+ cardElements,+ {+ y: -15,+ duration: 0.3,+ stagger: {each: 0.08, from: 'edges'},+ repeat: 1,+ yoyo: true,+ ease: 'power2.inOut',+ },+ 'metrics+=0.35',+ )+ .addLabel('outro', 4.65)+ .to(+ [...titleWords, ...metrics, ...selector('[data-kicker]')],+ {y: -34, opacity: 0, duration: 0.42, stagger: 0.035, ease: 'power2.in'},+ 'outro',+ )+ .to(+ cardElements,+ {+ y: 100,+ opacity: 0,+ scale: 0.82,+ duration: 0.55,+ stagger: 0.06,+ ease: 'back.in(1.3)',+ },+ 'outro+=0.08',+ )+ .fromTo(+ selector('[data-wipe]'),+ {scaleX: 0},+ {+ scaleX: 1,+ duration: 0.7,+ transformOrigin: '0% 50%',+ ease: 'expo.inOut',+ },+ 'outro+=0.35',+ )+ .from(+ selector('[data-final]'),+ {y: 54, opacity: 0, duration: 0.7, ease: 'power4.out'},+ 'outro+=0.86',+ );+ });++ return (+ <AbsoluteFill+ ref={scope}+ style={{+ background: '#090A0F',+ color: '#F7F7F2',+ fontFamily: 'Arial, Helvetica, sans-serif',+ overflow: 'hidden',+ }}+ >+ <div data-stage style={{position: 'absolute', inset: 0, opacity: 0}}>+ <div+ data-glow+ style={{+ position: 'absolute',+ width: 580,+ height: 580,+ left: -250,+ bottom: -260,+ borderRadius: '50%',+ background:+ 'radial-gradient(circle, rgba(124,92,255,.45), rgba(124,92,255,0) 68%)',+ filter: 'blur(12px)',+ }}+ />++ <div+ data-orbit+ style={{+ position: 'absolute',+ width: 700,+ height: 700,+ right: -330,+ top: -330,+ border: '1px solid rgba(184,255,90,.18)',+ borderRadius: '50%',+ }}+ >+ <div+ style={{+ position: 'absolute',+ width: 18,+ height: 18,+ left: 91,+ top: 78,+ borderRadius: '50%',+ background: '#B8FF5A',+ boxShadow: '0 0 38px #B8FF5A',+ }}+ />+ </div>++ <div style={{position: 'absolute', inset: '62px 74px'}}>+ <div+ data-kicker+ style={{+ fontSize: 14,+ fontWeight: 700,+ letterSpacing: '0.24em',+ color: '#B8FF5A',+ }}+ >+ REMOTION Γ GSAP Β· DETERMINISTIC ADAPTER+ </div>++ <div style={{marginTop: 22, perspective: 900}}>+ {title.map((word) => (+ <div+ key={word}+ style={{+ height: 82,+ overflow: 'hidden',+ fontSize: 76,+ fontWeight: 900,+ lineHeight: 0.98,+ letterSpacing: '-0.055em',+ }}+ >+ <div data-title-word>{word}</div>+ </div>+ ))}+ </div>++ <div+ data-rule+ style={{+ width: 600,+ height: 4,+ marginTop: 22,+ background: '#B8FF5A',+ }}+ />++ <div style={{display: 'flex', gap: 18, marginTop: 38}}>+ {cards.map((card) => (+ <div+ data-card+ key={card.number}+ style={{+ width: 258,+ height: 152,+ padding: '20px 22px',+ boxSizing: 'border-box',+ border: '1px solid rgba(255,255,255,.16)',+ borderRadius: 22,+ background:+ 'linear-gradient(145deg, rgba(255,255,255,.12), rgba(255,255,255,.045))',+ boxShadow: '0 24px 80px rgba(0,0,0,.35)',+ backdropFilter: 'blur(16px)',+ }}+ >+ <div+ style={{+ fontSize: 13,+ fontWeight: 800,+ color: card.color,+ letterSpacing: '0.15em',+ }}+ >+ {card.number}+ </div>+ <div+ style={{+ fontSize: 27,+ fontWeight: 800,+ marginTop: 48,+ letterSpacing: '-0.035em',+ }}+ >+ {card.label}+ </div>+ </div>+ ))}+ </div>++ <div+ style={{+ display: 'flex',+ gap: 34,+ marginTop: 30,+ color: 'rgba(247,247,242,.62)',+ fontSize: 13,+ fontWeight: 700,+ letterSpacing: '0.12em',+ }}+ >+ <div data-metric>FRAME β SECONDS</div>+ <div data-metric>PAUSED β SEEKED</div>+ <div data-metric>SAME FRAME β SAME PIXELS</div>+ </div>+ </div>++ <div+ data-wipe+ style={{+ position: 'absolute',+ inset: 0,+ background: '#B8FF5A',+ transform: 'scaleX(0)',+ }}+ />+ <div+ data-final+ style={{+ position: 'absolute',+ inset: 0,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ flexDirection: 'column',+ color: '#090A0F',+ }}+ >+ <div style={{fontSize: 18, fontWeight: 800, letterSpacing: '0.25em'}}>+ THE TIMELINE IS YOURS+ </div>+ <div+ style={{+ fontSize: 82,+ fontWeight: 900,+ letterSpacing: '-0.06em',+ marginTop: 8,+ }}+ >+ THE CLOCK IS REMOTION'S.+ </div>+ </div>+ </div>+ </AbsoluteFill>+ );+};++export default GsapShowcase;diff --git a/packages/example/src/Gsap/Surface.tsx b/packages/example/src/Gsap/Surface.tsxnew file mode 100644index 0000000000..8f7a850af3--- /dev/null+++ b/packages/example/src/Gsap/Surface.tsx@@ -0,0 +1,105 @@+import {useGsapTimeline} from '@remotion/gsap';+import React from 'react';+import {AbsoluteFill} from 'remotion';++const SurfaceFixture: React.FC = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline+ .set(selector('[data-panel]'), {opacity: 1, '--hue': 20})+ .to(+ selector('[data-panel]'),+ {+ x: 150,+ rotation: 270,+ borderRadius: 44,+ '--hue': 280,+ duration: 2,+ ease: 'none',+ },+ 0,+ )+ .to(+ selector('[data-svg-rect]'),+ {+ attr: {x: 188, rx: 24, fill: '#B8FF5A'},+ rotation: 90,+ transformOrigin: '50% 50%',+ duration: 2,+ ease: 'power2.inOut',+ },+ 0,+ )+ .to(+ selector('[data-pulse]'),+ {+ scale: 1.5,+ repeat: 1,+ yoyo: true,+ duration: 0.5,+ ease: 'sine.inOut',+ },+ 0.25,+ )+ .to(+ selector('[data-keyframe]'),+ {+ keyframes: [+ {y: -34, rotation: -20},+ {x: 80, y: 0, rotation: 20},+ {x: 160, y: -20, rotation: 0},+ ],+ duration: 2,+ ease: 'none',+ },+ 0,+ );+ });++ return (+ <AbsoluteFill+ ref={scope}+ style={{background: '#080910', overflow: 'hidden'}}+ >+ <div+ data-panel+ style={+ {+ '--hue': 20,+ position: 'absolute',+ width: 72,+ height: 72,+ left: 32,+ top: 26,+ opacity: 0,+ background: 'hsl(var(--hue) 90% 55%)',+ } as React.CSSProperties+ }+ />+ <svg width="320" height="180" viewBox="0 0 320 180">+ <rect+ data-svg-rect+ x="24"+ y="118"+ width="66"+ height="30"+ rx="2"+ fill="#7C5CFF"+ />+ <circle data-pulse cx="270" cy="45" r="16" fill="#FF5F8F" />+ </svg>+ <div+ data-keyframe+ style={{+ position: 'absolute',+ width: 24,+ height: 24,+ left: 65,+ bottom: 12,+ background: '#fff',+ }}+ />+ </AbsoluteFill>+ );+};++export default SurfaceFixture;diff --git a/packages/example/src/Gsap/SvgRoot.tsx b/packages/example/src/Gsap/SvgRoot.tsxnew file mode 100644index 0000000000..3e261b374d--- /dev/null+++ b/packages/example/src/Gsap/SvgRoot.tsx@@ -0,0 +1,26 @@+import {useGsapTimeline} from '@remotion/gsap';+import React from 'react';++const SvgRootFixture: React.FC = () => {+ const scope = useGsapTimeline<SVGSVGElement>(({timeline, selector}) =>+ timeline.to(selector('[data-root-circle]'), {+ attr: {cx: 80, fill: '#B8FF5A'},+ duration: 1,+ ease: 'none',+ }),+ );++ return (+ <svg+ ref={scope}+ width="100"+ height="100"+ viewBox="0 0 100 100"+ style={{background: '#000'}}+ >+ <circle data-root-circle cx="20" cy="50" r="14" fill="#7C5CFF" />+ </svg>+ );+};++export default SvgRootFixture;diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsxindex e9d275fc8d..b05075e278 100644--- a/packages/example/src/Root.tsx+++ b/packages/example/src/Root.tsx@@ -1901,6 +1901,88 @@ export const Index: React.FC = () => {}}/></Folder>+ <Folder name="gsap">+ <Composition+ id="gsap-showcase"+ lazyComponent={() => import('./Gsap/Showcase')}+ durationInFrames={210}+ fps={30}+ width={1280}+ height={720}+ />+ <Composition+ id="gsap-fps-24"+ lazyComponent={() => import('./Gsap/OpacityFixture')}+ durationInFrames={48}+ fps={24}+ width={100}+ height={100}+ />+ <Composition+ id="gsap-fps-30"+ lazyComponent={() => import('./Gsap/OpacityFixture')}+ durationInFrames={60}+ fps={30}+ width={100}+ height={100}+ />+ <Composition+ id="gsap-fps-60"+ lazyComponent={() => import('./Gsap/OpacityFixture')}+ durationInFrames={120}+ fps={60}+ width={100}+ height={100}+ />+ <Composition+ id="gsap-sequence"+ lazyComponent={() => import('./Gsap/Sequence')}+ durationInFrames={90}+ fps={30}+ width={100}+ height={100}+ />+ <Composition+ id="gsap-nested-sequence"+ lazyComponent={() => import('./Gsap/NestedSequence')}+ durationInFrames={100}+ fps={30}+ width={100}+ height={100}+ />+ <Composition+ id="gsap-surface"+ lazyComponent={() => import('./Gsap/Surface')}+ durationInFrames={75}+ fps={30}+ width={320}+ height={180}+ />+ <Composition+ id="gsap-overlap"+ lazyComponent={() => import('./Gsap/Overlap')}+ durationInFrames={90}+ fps={30}+ width={320}+ height={180}+ />+ <Composition+ id="gsap-same-property-overlap"+ lazyComponent={() => import('./Gsap/SamePropertyOverlap')}+ durationInFrames={60}+ fps={30}+ width={320}+ height={120}+ />+ <Composition+ id="gsap-svg-root"+ lazyComponent={() => import('./Gsap/SvgRoot')}+ durationInFrames={60}+ fps={30}+ width={100}+ height={100}+ />+ </Folder><Folder name="lottie"><Compositionid="cybertruck"diff --git a/packages/example/tsconfig.json b/packages/example/tsconfig.jsonindex 5b32c272c3..0e2830b518 100644--- a/packages/example/tsconfig.json+++ b/packages/example/tsconfig.json@@ -25,6 +25,7 @@{"path": "../gif"},{"path": "../fonts"},{"path": "../lambda"},+ {"path": "../gsap"},{"path": "../lottie"},{"path": "../media-utils"},{"path": "../motion-blur"},diff --git a/packages/gsap/.npmignore b/packages/gsap/.npmignorenew file mode 100644index 0000000000..5ade67cf70--- /dev/null+++ b/packages/gsap/.npmignore@@ -0,0 +1,12 @@+dist/test/**+src+eslint.config.mjs+tsconfig.tsbuildinfo+*.tgz+.turbo+tsconfig.json+.prettierrc.js+bundle.ts+dist/cjs/test+happydom.ts+bunfig.tomldiff --git a/packages/gsap/README.md b/packages/gsap/README.mdnew file mode 100644index 0000000000..1eb1443a7d--- /dev/null+++ b/packages/gsap/README.md@@ -0,0 +1,18 @@+# @remotion/gsap++Drive GSAP timelines from the Remotion frame++[](https://npmcharts.com/compare/@remotion/gsap?minimal=true)++## Installation++```bash+npm install @remotion/gsap --save-exact+```++When installing a Remotion package, make sure to align the version of all `remotion` and `@remotion/*` packages to the same version.+Remove the `^` character from the version number to use the exact version.++## Usage++See the [documentation](https://www.remotion.dev/docs/gsap) for more information.diff --git a/packages/gsap/bundle.ts b/packages/gsap/bundle.tsnew file mode 100644index 0000000000..19e7843984--- /dev/null+++ b/packages/gsap/bundle.ts@@ -0,0 +1,47 @@+import path from 'path';+import {build} from 'bun';++if (process.env.NODE_ENV !== 'production') {+ throw new Error('This script must be run using NODE_ENV=production');+}++console.time('Generated.');+const output = await build({+ entrypoints: ['src/index.ts'],+ naming: '[name].mjs',+ external: [+ 'gsap',+ 'remotion',+ 'remotion/no-react',+ 'react',+ 'react/jsx-runtime',+ 'react/jsx-dev-runtime',+ 'react-dom',+ ],+});++if (!output.success) {+ console.log(output.logs.join('\n'));+ process.exit(1);+}++for (const file of output.outputs) {+ const str = await file.text();+ const out = path.join('dist', 'esm', file.path);++ 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.+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();+ if (!content.startsWith(gsapReference)) {+ await Bun.write(declaration, gsapReference + content);+ }+}++console.timeEnd('Generated.');diff --git a/packages/gsap/bunfig.toml b/packages/gsap/bunfig.tomlnew file mode 100644index 0000000000..d20eff30d4--- /dev/null+++ b/packages/gsap/bunfig.toml@@ -0,0 +1,2 @@+[test]+preload = "./happydom.ts"diff --git a/packages/gsap/eslint.config.mjs b/packages/gsap/eslint.config.mjsnew file mode 100644index 0000000000..ab29acaba0--- /dev/null+++ b/packages/gsap/eslint.config.mjs@@ -0,0 +1,7 @@+import {remotionFlatConfig} from '@remotion/eslint-config-internal';++const config = remotionFlatConfig({react: true});++export default {+ ...config,+};diff --git a/packages/gsap/happydom.ts b/packages/gsap/happydom.tsnew file mode 100644index 0000000000..3194d2051d--- /dev/null+++ b/packages/gsap/happydom.ts@@ -0,0 +1,6 @@+import {GlobalRegistrator} from '@happy-dom/global-registrator';++GlobalRegistrator.register();+window.origin = 'http://localhost:3000';+// @ts-expect-error+window.remotion_staticBase = '/static-abcdef';diff --git a/packages/gsap/package.json b/packages/gsap/package.jsonnew file mode 100644index 0000000000..ead167d053--- /dev/null+++ b/packages/gsap/package.json@@ -0,0 +1,64 @@+{+ "name": "@remotion/gsap",+ "version": "4.0.515",+ "description": "Drive GSAP timelines from the Remotion frame",+ "main": "dist/index.js",+ "types": "dist/index.d.ts",+ "module": "dist/esm/index.mjs",+ "repository": {+ "url": "https://github.com/remotion-dev/remotion/tree/main/packages/gsap"+ },+ "type": "module",+ "scripts": {+ "test": "bun test src/test",+ "formatting": "oxfmt src --check",+ "format": "oxfmt src",+ "lint": "eslint src",+ "watch": "tsgo -w",+ "make": "tsgo && bun --env-file=../.env.bundle bundle.ts"+ },+ "author": "Brayden Blackwell",+ "contributors": [],+ "license": "MIT",+ "bugs": {+ "url": "https://github.com/remotion-dev/remotion/issues"+ },+ "dependencies": {+ "remotion": "workspace:*"+ },+ "peerDependencies": {+ "gsap": ">=3.12.0 <4",+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ },+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "module": "./dist/esm/index.mjs",+ "import": "./dist/esm/index.mjs"+ },+ "./package.json": "./package.json"+ },+ "devDependencies": {+ "react": "catalog:",+ "react-dom": "catalog:",+ "@types/react": "catalog:",+ "@types/react-dom": "catalog:",+ "@remotion/eslint-config-internal": "workspace:*",+ "@happy-dom/global-registrator": "14.5.1",+ "eslint": "catalog:",+ "gsap": "3.15.0",+ "@typescript/native-preview": "catalog:"+ },+ "keywords": [+ "remotion",+ "gsap",+ "animation",+ "video",+ "react"+ ],+ "publishConfig": {+ "access": "public"+ },+ "homepage": "https://www.remotion.dev/docs/gsap"+}diff --git a/packages/gsap/src/frame-time.ts b/packages/gsap/src/frame-time.tsnew file mode 100644index 0000000000..1e834118f7--- /dev/null+++ b/packages/gsap/src/frame-time.ts@@ -0,0 +1,13 @@+export const frameToSeconds = (frame: number, fps: number): number => {+ if (!Number.isFinite(frame)) {+ throw new TypeError(`frame must be finite, received ${String(frame)}`);+ }++ if (!Number.isFinite(fps) || fps <= 0) {+ throw new RangeError(+ `fps must be a positive finite number, received ${String(fps)}`,+ );+ }++ return Math.max(0, frame) / fps;+};diff --git a/packages/gsap/src/index.ts b/packages/gsap/src/index.tsnew file mode 100644index 0000000000..47a33ce6e0--- /dev/null+++ b/packages/gsap/src/index.ts@@ -0,0 +1,7 @@+export {useGsapTimeline} from './use-gsap-timeline';+export type {+ GsapTimelineBuildContext,+ GsapTimelineBuilder,+ GsapScopeRef,+ UseGsapTimelineOptions,+} from './use-gsap-timeline';diff --git a/packages/gsap/src/test/frame-time.test.ts b/packages/gsap/src/test/frame-time.test.tsnew file mode 100644index 0000000000..6c5b42e8c6--- /dev/null+++ b/packages/gsap/src/test/frame-time.test.ts@@ -0,0 +1,22 @@+import {describe, expect, it} from 'bun:test';+import {frameToSeconds} from '../frame-time';++describe('frameToSeconds', () => {+ it('converts frames into absolute timeline seconds', () => {+ expect(frameToSeconds(45, 30)).toBe(1.5);+ expect(frameToSeconds(24, 24)).toBe(1);+ expect(frameToSeconds(120, 60)).toBe(2);+ });++ it('clamps premount frames by default', () => {+ expect(frameToSeconds(-12, 30)).toBe(0);+ });++ it('rejects invalid frame and fps values', () => {+ expect(() => frameToSeconds(Number.NaN, 30)).toThrow(TypeError);+ expect(() => frameToSeconds(10, 0)).toThrow(RangeError);+ expect(() => frameToSeconds(10, Number.POSITIVE_INFINITY)).toThrow(+ RangeError,+ );+ });+});diff --git a/packages/gsap/src/test/use-gsap-timeline.test.tsx b/packages/gsap/src/test/use-gsap-timeline.test.tsxnew file mode 100644index 0000000000..37d33bf7e5--- /dev/null+++ b/packages/gsap/src/test/use-gsap-timeline.test.tsx@@ -0,0 +1,901 @@+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ mock,+ spyOn,+} from 'bun:test';+import {gsap} from 'gsap';+import React, {Component, StrictMode, act, type ReactNode} from 'react';+import {createRoot, type Root} from 'react-dom/client';+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.+mock.module('remotion', () => ({+ useCurrentFrame: () => remotionClock.frame,+ useVideoConfig: () => ({fps: remotionClock.fps}),+}));++(+ globalThis as typeof globalThis & {IS_REACT_ACT_ENVIRONMENT: boolean}+).IS_REACT_ACT_ENVIRONMENT = true;++const opacity = (element: Element) =>+ Number.parseFloat((element as HTMLElement).style.opacity);++class ErrorBoundary extends Component<+ {children: ReactNode},+ {failed: boolean}+> {+ state = {failed: false};++ static getDerivedStateFromError() {+ return {failed: true};+ }++ render() {+ return this.state.failed ? (+ <div data-error-boundary />+ ) : (+ this.props.children+ );+ }+}++const Harness = ({distance}: {readonly distance: number}) => {+ const scope = useGsapTimeline<HTMLDivElement>(+ ({timeline, selector}) => {+ timeline.fromTo(+ selector('[data-box]'),+ {opacity: 0},+ {opacity: distance, duration: 1, ease: 'none'},+ );+ },+ {dependencies: [distance]},+ );++ return (+ <div ref={scope}>+ <div data-box style={{opacity: 0.25}} />+ </div>+ );+};++describe('useGsapTimeline', () => {+ let container: HTMLDivElement;+ let root: Root;++ const render = async (node: ReactNode) => {+ await act(async () => root.render(node));+ };++ const setFrame = async (frame: number, node: ReactNode) => {+ remotionClock.frame = frame;+ await render(node);+ };++ beforeEach(() => {+ remotionClock.frame = 0;+ remotionClock.fps = 30;+ container = document.createElement('div');+ document.body.append(container);+ root = createRoot(container);+ });++ afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ });++ it('seeks directly from Remotion frame to GSAP time', async () => {+ await setFrame(15, <Harness distance={1} />);+ expect(opacity(container.querySelector('[data-box]')!)).toBeCloseTo(0.5, 4);+ });++ it('is deterministic while seeking backward and revisiting frames', async () => {+ await setFrame(30, <Harness distance={1} />);+ expect(opacity(container.querySelector('[data-box]')!)).toBeCloseTo(1, 4);++ await setFrame(9, <Harness distance={1} />);+ const firstVisit = opacity(container.querySelector('[data-box]')!);+ expect(firstVisit).toBeCloseTo(0.3, 4);++ await setFrame(24, <Harness distance={1} />);+ await setFrame(9, <Harness distance={1} />);+ expect(opacity(container.querySelector('[data-box]')!)).toBeCloseTo(+ firstVisit,+ 6,+ );+ });++ it('rejects callbacks instead of allowing render-time side effects', async () => {+ const onUpdate = mock(() => undefined);+ const CallbackHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.to(selector('[data-callback]'), {opacity: 1, onUpdate});+ });++ return (+ <div ref={scope}>+ <div data-callback />+ </div>+ );+ };++ await expect(setFrame(30, <CallbackHarness />)).rejects.toThrow(+ 'does not allow timeline callbacks (onUpdate)',+ );+ expect(onUpdate).not.toHaveBeenCalled();+ });++ it('rebuilds from explicit dependencies and seeks the replacement timeline', async () => {+ await setFrame(15, <Harness distance={1} />);+ expect(opacity(container.querySelector('[data-box]')!)).toBeCloseTo(0.5, 4);++ await setFrame(15, <Harness distance={0.6} />);+ expect(opacity(container.querySelector('[data-box]')!)).toBeCloseTo(0.3, 4);+ });++ it('scopes matching selectors to each hook instance', async () => {+ await setFrame(+ 15,+ <>+ <Harness distance={1} />+ <Harness distance={0.4} />+ </>,+ );++ const boxes = container.querySelectorAll('[data-box]');+ expect(opacity(boxes[0]!)).toBeCloseTo(0.5, 4);+ expect(opacity(boxes[1]!)).toBeCloseTo(0.2, 4);+ });++ it('survives Strict Mode setup-cleanup-setup without duplicate playback', async () => {+ await setFrame(+ 18,+ <StrictMode>+ <Harness distance={1} />+ </StrictMode>,+ );++ expect(opacity(container.querySelector('[data-box]')!)).toBeCloseTo(0.6, 4);+ });++ it('clamps premount frames to the start state', async () => {+ await setFrame(-20, <Harness distance={1} />);+ expect(opacity(container.querySelector('[data-box]')!)).toBeCloseTo(0, 4);+ });++ it('uses the latest fps without rebuilding the timeline', async () => {+ await setFrame(15, <Harness distance={1} />);+ expect(opacity(container.querySelector('[data-box]')!)).toBeCloseTo(0.5, 4);++ remotionClock.fps = 60;+ await setFrame(15, <Harness distance={1} />);+ expect(opacity(container.querySelector('[data-box]')!)).toBeCloseTo(+ 0.25,+ 4,+ );+ });++ it('holds the final state after the timeline duration', async () => {+ await setFrame(300, <Harness distance={0.8} />);+ expect(opacity(container.querySelector('[data-box]')!)).toBeCloseTo(0.8, 4);+ });++ it('applies zero-duration set operations at frame zero', async () => {+ const SetHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.set(selector('[data-set]'), {opacity: 1});+ });++ return (+ <div ref={scope}>+ <div data-set style={{opacity: 0.25}} />+ </div>+ );+ };++ await setFrame(0, <SetHarness />);+ expect(opacity(container.querySelector('[data-set]')!)).toBe(1);+ });++ it('rejects builders that start wall-clock playback', async () => {+ const UnsafeHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline}) =>+ timeline.play(),+ );+ return <div ref={scope} />;+ };++ await expect(setFrame(0, <UnsafeHarness />)).rejects.toThrow(+ 'builders must not start playback',+ );+ });++ it('rejects playback before play-then-pause can evade the final state check', async () => {+ const UnsafeHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline}) => {+ timeline.play().pause();+ });+ return <div ref={scope} />;+ };++ await expect(setFrame(0, <UnsafeHarness />)).rejects.toThrow(+ 'builders must not start playback',+ );++ const UnpausedHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline}) => {+ timeline.paused(false);+ });+ return <div ref={scope} />;+ };++ await expect(setFrame(0, <UnpausedHarness />)).rejects.toThrow(+ 'builders must not start playback',+ );+ });++ it.each([+ ['seek', (clock: gsap.core.Timeline) => clock.seek(1)],+ ['totalTime', (clock: gsap.core.Timeline) => clock.totalTime(1)],+ ['progress', (clock: gsap.core.Timeline) => clock.progress(0.5)],+ ['tweenTo', (clock: gsap.core.Timeline) => clock.tweenTo(1)],+ ['pause', (clock: gsap.core.Timeline) => clock.pause()],+ ['kill', (clock: gsap.core.Timeline) => clock.kill()],+ ] as const)(+ 'rejects manual %s even when the timeline is aliased',+ async (_method, invoke) => {+ const UnsafeHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline: clock}) => {+ invoke(clock);+ });+ return <div ref={scope} />;+ };++ await expect(setFrame(0, <UnsafeHarness />)).rejects.toThrow(+ /useGsapTimeline owns timeline/,+ );+ },+ );++ 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.+ const DurationHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.fromTo(+ selector('[data-shaped]'),+ {opacity: 0},+ {opacity: 1, duration: 2, ease: 'none'},+ );+ timeline.duration(1);+ });++ return (+ <div ref={scope}>+ <div data-shaped />+ </div>+ );+ };++ await expect(setFrame(15, <DurationHarness />)).rejects.toThrow(+ 'does not support timeline.duration(value)',+ );++ const TimeScaleHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline}) => {+ timeline.timeScale(2);+ });++ return <div ref={scope} />;+ };++ await expect(setFrame(0, <TimeScaleHarness />)).rejects.toThrow(+ 'does not support timeline.timeScale(value)',+ );+ });++ 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.+ const ConciseSetHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({selector}) =>+ gsap.set(selector('[data-concise]'), {opacity: 0.75}),+ );++ return (+ <div ref={scope}>+ <div data-concise />+ </div>+ );+ };++ await setFrame(0, <ConciseSetHarness />);+ expect(opacity(container.querySelector('[data-concise]')!)).toBe(0.75);+ });++ 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.+ const NestedSetHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.to(selector('[data-nested-set]'), {+ opacity: 0.5,+ duration: 3,+ ease: 'none',+ });+ const nested = gsap.timeline();+ nested.set(+ selector('[data-nested-set]'),+ {backgroundColor: 'rgb(9, 8, 7)'},+ 0.5,+ );+ timeline.add(nested, 1.5);+ });++ return (+ <div ref={scope}>+ <div data-nested-set style={{opacity: 1}} />+ </div>+ );+ };++ // Frame 60 at 30fps = 2s = exactly the nested set's root time (1.5 + 0.5).+ await setFrame(60, <NestedSetHarness />);+ const element = container.querySelector('[data-nested-set]') as HTMLElement;+ expect(element.style.backgroundColor).toBe('rgb(9, 8, 7)');+ });++ it('rejects asynchronous builders', async () => {+ const AsyncHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(async () => undefined);+ return <div ref={scope} />;+ };++ await expect(setFrame(0, <AsyncHarness />)).rejects.toThrow(+ 'builders must be synchronous',+ );+ });++ it('rejects callback methods before they can execute', async () => {+ const callback = mock(() => undefined);+ const CallHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline}) =>+ timeline.call(callback),+ );+ return <div ref={scope} />;+ };++ await expect(setFrame(0, <CallHarness />)).rejects.toThrow(+ 'does not allow timeline.call()',+ );+ expect(callback).not.toHaveBeenCalled();+ });++ it('rejects eventCallback and then callbacks at registration time', async () => {+ const callback = mock(() => undefined);+ const EventCallbackHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline}) => {+ timeline.eventCallback('onComplete', callback);+ });+ return <div ref={scope} />;+ };++ await expect(setFrame(0, <EventCallbackHarness />)).rejects.toThrow(+ 'does not allow timeline.eventCallback()',+ );+ expect(callback).not.toHaveBeenCalled();++ const ThenHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline}) => {+ timeline.then(callback);+ });+ return <div ref={scope} />;+ };++ await expect(setFrame(0, <ThenHarness />)).rejects.toThrow(+ 'does not allow timeline.then()',+ );+ expect(callback).not.toHaveBeenCalled();+ });++ it('allows concise builders that return the chained timeline', async () => {+ const ChainedHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) =>+ timeline.fromTo(+ selector('[data-chain]'),+ {opacity: 0},+ {opacity: 1, duration: 1, ease: 'none'},+ ),+ );++ return (+ <div ref={scope}>+ <div data-chain />+ </div>+ );+ };++ await setFrame(15, <ChainedHarness />);+ expect(opacity(container.querySelector('[data-chain]')!)).toBeCloseTo(+ 0.5,+ 4,+ );+ });++ it('reverts the previous context before rebuilding from dependencies', async () => {+ const RebuildHarness = ({transform}: {readonly transform: boolean}) => {+ const scope = useGsapTimeline<HTMLDivElement>(+ ({timeline, selector}) => {+ if (transform) {+ timeline.set(selector('[data-rebuild]'), {'--offset': '100px'});+ } else {+ timeline.set(selector('[data-rebuild]'), {opacity: 0.5});+ }+ },+ {dependencies: [transform]},+ );++ return (+ <div ref={scope}>+ <div data-rebuild style={{opacity: 0.25}} />+ </div>+ );+ };++ await setFrame(0, <RebuildHarness transform />);+ expect(+ (+ container.querySelector('[data-rebuild]') as HTMLElement+ ).style.getPropertyValue('--offset'),+ ).toBe('100px');++ await setFrame(0, <RebuildHarness transform={false} />);+ const rebuilt = container.querySelector('[data-rebuild]') as HTMLElement;+ expect(rebuilt.style.getPropertyValue('--offset')).toBe('');+ expect(opacity(rebuilt)).toBe(0.5);+ });++ it('reverts GSAP mutations when a builder throws', async () => {+ let retainedElement: HTMLDivElement | null = null;+ const consoleError = spyOn(console, 'error').mockImplementation(+ () => undefined,+ );++ const ThrowingHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({selector}) => {+ gsap.set(selector('[data-throw]'), {opacity: 0});+ throw new Error('intentional builder failure');+ });++ return (+ <div ref={scope}>+ <div+ ref={(element) => {+ if (element) {+ retainedElement = element;+ }+ }}+ data-throw+ style={{opacity: 0.25}}+ />+ </div>+ );+ };++ await setFrame(+ 0,+ <ErrorBoundary>+ <ThrowingHarness />+ </ErrorBoundary>,+ );++ expect(retainedElement).not.toBeNull();+ expect((retainedElement as HTMLDivElement | null)?.style.opacity).toBe(+ '0.25',+ );+ expect(container.querySelector('[data-error-boundary]')).not.toBeNull();+ consoleError.mockRestore();+ });++ it('rejects plain-object tween targets that would freeze in stills', async () => {+ const PojoHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline}) => {+ const state = {dist: 0, glow: 0.2};+ timeline.to(state, {dist: 100, duration: 1, ease: 'none'});+ });++ return <div ref={scope} />;+ };++ await expect(setFrame(0, <PojoHarness />)).rejects.toThrow(+ 'must target DOM or SVG elements',+ );+ await expect(setFrame(0, <PojoHarness />)).rejects.toThrow(+ 'plain object {dist, glow}',+ );+ });++ it('rejects plain-object targets hidden inside nested timelines', async () => {+ const NestedPojoHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.to(selector('[data-real]'), {opacity: 1, duration: 0.5});+ const nested = gsap.timeline();+ nested.to({progress: 0}, {progress: 1, duration: 1});+ timeline.add(nested, 0.25);+ });++ return (+ <div ref={scope}>+ <div data-real />+ </div>+ );+ };++ await expect(setFrame(0, <NestedPojoHarness />)).rejects.toThrow(+ 'must target DOM or SVG elements',+ );+ });++ it('renders a zero-duration set at time 0 on a fresh mount at frame 0', async () => {+ const SetHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.set(selector('[data-set]'), {backgroundColor: 'rgb(1, 2, 3)'});+ timeline.fromTo(+ selector('[data-set]'),+ {opacity: 0},+ {opacity: 1, duration: 1, ease: 'none'},+ );+ });++ return (+ <div ref={scope}>+ <div data-set />+ </div>+ );+ };++ await setFrame(0, <SetHarness />);+ const element = container.querySelector('[data-set]') as HTMLElement;+ expect(element.style.backgroundColor).toBe('rgb(1, 2, 3)');+ expect(opacity(element)).toBe(0);+ });++ it('renders a mid-timeline set when a fresh mount lands exactly on it', async () => {+ const MidSetHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.to(selector('[data-mid]'), {+ opacity: 0.5,+ duration: 1,+ ease: 'none',+ });+ timeline.set(+ selector('[data-mid]'),+ {backgroundColor: 'rgb(4, 5, 6)'},+ 1,+ );+ });++ return (+ <div ref={scope}>+ <div data-mid style={{opacity: 1}} />+ </div>+ );+ };++ await setFrame(30, <MidSetHarness />);+ const element = container.querySelector('[data-mid]') as HTMLElement;+ expect(element.style.backgroundColor).toBe('rgb(4, 5, 6)');+ });++ it('primes safely when the timeline contains infinite repeats', async () => {+ const InfiniteHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.set(selector('[data-inf]'), {+ backgroundColor: 'rgb(7, 8, 9)',+ });+ timeline.to(+ selector('[data-inf]'),+ {rotation: 360, duration: 2, ease: 'none', repeat: -1},+ 0,+ );+ });++ return (+ <div ref={scope}>+ <div data-inf />+ </div>+ );+ };++ await setFrame(15, <InfiniteHarness />);+ const element = container.querySelector('[data-inf]') as HTMLElement;+ expect(element.style.backgroundColor).toBe('rgb(7, 8, 9)');+ expect(element.style.transform).toContain('rotate(90deg)');+ });++ it('rejects freestanding gsap.to animations that never join the timeline', async () => {+ const StrayHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({selector, timeline}) => {+ timeline.to(selector('[data-stray]'), {opacity: 1, duration: 0.5});+ gsap.to(selector('[data-stray]'), {x: 500, duration: 1});+ });++ return (+ <div ref={scope}>+ <div data-stray />+ </div>+ );+ };++ await expect(setFrame(0, <StrayHarness />)).rejects.toThrow(+ 'not attached to the provided timeline',+ );+ });++ it('rejects gsap.delayedCall scheduled from a builder', async () => {+ const spy = mock(() => undefined);+ const DelayedHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.to(selector('[data-delayed]'), {opacity: 1, duration: 0.5});+ gsap.delayedCall(0.05, spy);+ });++ return (+ <div ref={scope}>+ <div data-delayed />+ </div>+ );+ };++ await expect(setFrame(0, <DelayedHarness />)).rejects.toThrow(+ 'wall-clock animation with callbacks',+ );+ expect(spy).not.toHaveBeenCalled();+ });++ it('rejects gsap.ticker callbacks registered from a builder', async () => {+ const TickerHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.to(selector('[data-tick]'), {opacity: 1, duration: 0.5});+ gsap.ticker.add(() => undefined);+ });++ return (+ <div ref={scope}>+ <div data-tick />+ </div>+ );+ };++ await expect(setFrame(0, <TickerHarness />)).rejects.toThrow(+ 'must not register gsap.ticker callbacks',+ );+ });++ it('allows raw zero-duration gsap.set for static state', async () => {+ const StaticHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ gsap.set(selector('[data-static]'), {+ backgroundColor: 'rgb(9, 9, 9)',+ });+ timeline.fromTo(+ selector('[data-static]'),+ {opacity: 0},+ {opacity: 1, duration: 1, ease: 'none'},+ );+ });++ return (+ <div ref={scope}>+ <div data-static />+ </div>+ );+ };++ await setFrame(15, <StaticHarness />);+ const element = container.querySelector('[data-static]') as HTMLElement;+ expect(element.style.backgroundColor).toBe('rgb(9, 9, 9)');+ expect(opacity(element)).toBeCloseTo(0.5, 4);+ });++ it('rejects unseeded random() string values', async () => {+ const RandomHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.to(selector('[data-random]'), {+ x: 'random(0, 1000)',+ duration: 1,+ });+ });++ return (+ <div ref={scope}>+ <div data-random />+ </div>+ );+ };++ await expect(setFrame(0, <RandomHarness />)).rejects.toThrow(+ 'nondeterministic tween configuration',+ );+ });++ it('rejects random-order staggers and repeatRefresh', async () => {+ const StaggerHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.to(selector('[data-item]'), {+ opacity: 1,+ duration: 0.5,+ stagger: {each: 0.1, from: 'random'},+ });+ });++ return (+ <div ref={scope}>+ <div data-item />+ <div data-item />+ </div>+ );+ };++ const RefreshHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.to(selector('[data-refresh]'), {+ x: 100,+ duration: 0.5,+ repeat: 2,+ repeatRefresh: true,+ });+ });++ return (+ <div ref={scope}>+ <div data-refresh />+ </div>+ );+ };++ await expect(setFrame(0, <StaggerHarness />)).rejects.toThrow(+ "stagger: {from: 'random'}",+ );+ await expect(setFrame(0, <RefreshHarness />)).rejects.toThrow(+ 'repeatRefresh: true',+ );+ });++ it('renders overlapping same-property tweens identically for any frame-visit path', async () => {+ const OverlapHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.to(+ selector('[data-overlap]'),+ {x: 200, duration: 1, ease: 'none'},+ 0,+ );+ timeline.to(+ selector('[data-overlap]'),+ {x: 0, duration: 1, ease: 'none'},+ 0.5,+ );+ });++ return (+ <div ref={scope}>+ <div data-overlap />+ </div>+ );+ };++ const readX = () =>+ (container.querySelector('[data-overlap]') as HTMLElement).style+ .transform;++ await setFrame(23, <OverlapHarness />);+ const direct = readX();++ await act(async () => root.unmount());+ root = createRoot(container);+ remotionClock.frame = 0;+ await render(<OverlapHarness />);+ for (let frame = 1; frame <= 23; frame += 1) {+ await setFrame(frame, <OverlapHarness />);+ }++ const sequential = readX();++ expect(direct).toBe(sequential);+ });++ 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().+ const StaggerHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.fromTo(+ selector('[data-w]'),+ {opacity: 0, y: 44},+ {opacity: 1, y: 0, duration: 0.38, ease: 'power3.out', stagger: 0.06},+ 0.05,+ );+ });+ return (+ <div ref={scope}>+ <span data-w>a</span>+ <span data-w>b</span>+ <span data-w>c</span>+ </div>+ );+ };++ const HostApp = () => {+ const [doc] = React.useState(+ '## Skill: remotion-core β never use unseeded randomness; use seeded random() instead.',+ );+ return (+ <div data-doc={doc.length}>+ <StaggerHarness />+ </div>+ );+ };++ await setFrame(30, <HostApp />);+ const words = [...container.querySelectorAll('[data-w]')];+ expect(words).toHaveLength(3);+ expect(opacity(words[0] as HTMLElement)).toBe(1);+ });++ it('does not flag prose that merely mentions random()', async () => {+ const ProseHarness = () => {+ const scope = useGsapTimeline<HTMLDivElement>(({timeline, selector}) => {+ timeline.set(selector('[data-prose]'), {+ '--note': 'we use seeded random() here',+ });+ timeline.to(selector('[data-prose]'), {opacity: 0.5, duration: 1});+ });+ return (+ <div ref={scope}>+ <div data-prose />+ </div>+ );+ };++ await setFrame(15, <ProseHarness />);+ expect(+ (+ container.querySelector('[data-prose]') as HTMLElement+ ).style.getPropertyValue('--note'),+ ).toBe('we use seeded random() here');+ });++ it('allows SVG element targets through the plain-object guard', async () => {+ const SvgHarness = () => {+ const scope = useGsapTimeline<SVGSVGElement>(({timeline, selector}) => {+ timeline.fromTo(+ selector('[data-dot]'),+ {attr: {r: 0}},+ {attr: {r: 10}, duration: 1, ease: 'none'},+ );+ });++ return (+ <svg ref={scope}>+ <circle data-dot r={0} />+ </svg>+ );+ };++ await setFrame(15, <SvgHarness />);+ expect(container.querySelector('[data-dot]')!.getAttribute('r')).toBe('5');+ });+});diff --git a/packages/gsap/src/use-gsap-timeline.ts b/packages/gsap/src/use-gsap-timeline.tsnew file mode 100644index 0000000000..9917c5dd42--- /dev/null+++ b/packages/gsap/src/use-gsap-timeline.ts@@ -0,0 +1,640 @@+/// <reference types="gsap" />+import {gsap} from 'gsap';+import {type DependencyList, useLayoutEffect, useRef} from 'react';+import {useCurrentFrame, useVideoConfig} from 'remotion';+import {frameToSeconds} from './frame-time';++export type GsapTimelineBuildContext<T extends Element> = {+ /** A package-owned timeline that is already paused at time zero. */+ timeline: gsap.core.Timeline;+ /** The mounted element attached to the returned ref. */+ scope: T;+ /** A GSAP selector restricted to descendants of the scope element. */+ selector: gsap.utils.SelectorFunc;+};++export type GsapTimelineBuilder<T extends Element> = (+ context: GsapTimelineBuildContext<T>,+) => unknown;++export type UseGsapTimelineOptions = {+ /** Rebuild the timeline when one of these values changes. */+ dependencies?: DependencyList;+};++/** A React 18/19-compatible object ref for the scoped HTML or SVG root. */+export type GsapScopeRef<T extends Element> = {+ current: T | null;+};++const EMPTY_DEPENDENCIES: DependencyList = [];+const CALLBACK_KEYS = [+ 'onStart',+ 'onUpdate',+ 'onComplete',+ 'onRepeat',+ 'onReverseComplete',+ 'onInterrupt',+] as const;++const getTimelineAnimations = (+ timeline: gsap.core.Timeline,+): gsap.core.Animation[] => [+ timeline,+ ...timeline.getChildren(true, true, true),+];++const animationVars = (+ animation: gsap.core.Animation,+): 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.+const isWalkable = (value: unknown): value is object => {+ if (typeof value !== 'object' || value === null) return false;+ if (Array.isArray(value)) return true;+ const proto = Object.getPrototypeOf(value) as object | null;+ return proto === Object.prototype || proto === null;+};++const findCallbacksInValue = (+ value: unknown,+ seen = new Set<object>(),+): string[] => {+ if (!isWalkable(value) || seen.has(value)) {+ return [];+ }++ seen.add(value);+ const entries = Array.isArray(value)+ ? value.map((entry, index) => [String(index), entry] as const)+ : Object.entries(value);+ const found: string[] = [];++ for (const [key, nestedValue] of entries) {+ if (+ CALLBACK_KEYS.includes(key as (typeof CALLBACK_KEYS)[number]) &&+ typeof nestedValue === 'function'+ ) {+ found.push(key);+ }++ found.push(...findCallbacksInValue(nestedValue, seen));+ }++ return [...new Set(found)];+};++const findTimelineCallbacks = (timeline: gsap.core.Timeline): string[] => {+ const animations = getTimelineAnimations(timeline);+ return [+ ...new Set(+ animations.flatMap((animation) =>+ findCallbacksInValue(animationVars(animation)),+ ),+ ),+ ];+};++// nodeType instead of instanceof keeps the check correct across realms+// (renderer processes, jsdom, iframes) where Element identity differs.+const isElementTarget = (target: unknown): boolean =>+ typeof target === 'object' &&+ target !== null &&+ (target as {nodeType?: unknown}).nodeType === 1;++const describeTarget = (target: unknown): string => {+ if (target === null) {+ return 'null';+ }++ if (typeof target !== 'object') {+ return typeof target;+ }++ // GSAP stamps internal bookkeeping onto tween targets; hide it so the+ // error names the author's own 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 ? ', β¦' : ''}}`;+};++const findNonElementTargets = (timeline: gsap.core.Timeline): string[] => {+ const found: string[] = [];+ for (const animation of getTimelineAnimations(timeline)) {+ const targets = (animation as {targets?: () => unknown[]}).targets?.();+ if (!targets) {+ continue;+ }++ for (const target of targets) {+ if (!isElementTarget(target)) {+ found.push(describeTarget(target));+ }+ }+ }++ 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.+const GSAP_RANDOM_TOKEN = /random\(\s*(-?[\d.]|\[)/;++const findNondeterministicVars = (+ value: unknown,+ seen = new Set<object>(),+): string[] => {+ if (typeof value === 'string') {+ return GSAP_RANDOM_TOKEN.test(value) ? [`"${value.slice(0, 120)}"`] : [];+ }++ if (!isWalkable(value) || seen.has(value)) {+ return [];+ }++ seen.add(value);+ const found: string[] = [];+ const record = value as Record<string, unknown>;+ if (!Array.isArray(value)) {+ if (record.repeatRefresh === true) {+ found.push('repeatRefresh: true');+ }++ const {stagger} = record;+ if (+ typeof stagger === 'object' &&+ stagger !== null &&+ (stagger as {from?: unknown}).from === 'random'+ ) {+ found.push("stagger: {from: 'random'}");+ }+ }++ for (const nested of Array.isArray(value) ? value : Object.values(record)) {+ found.push(...findNondeterministicVars(nested, seen));+ }++ return [...new Set(found)];+};++const findTimelineNondeterminism = (timeline: gsap.core.Timeline): string[] => {+ const animations = getTimelineAnimations(timeline);+ return [+ ...new Set(+ animations.flatMap((animation) =>+ findNondeterministicVars(animationVars(animation)),+ ),+ ),+ ];+};++// 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.+const findStrayAnimations = (+ timeline: gsap.core.Timeline,+ preexisting: Set<gsap.core.Animation>,+): string[] => {+ const owned = new Set(getTimelineAnimations(timeline));+ const problems: string[] = [];+ for (const animation of gsap.globalTimeline.getChildren(true, true, true)) {+ if (owned.has(animation) || preexisting.has(animation)) {+ continue;+ }++ const vars = animationVars(animation);+ const callbacks = findCallbacksInValue(vars);+ const delay = typeof vars.delay === 'number' ? vars.delay : 0;+ if (callbacks.length > 0) {+ problems.push(+ `a wall-clock animation with callbacks (${callbacks.join(', ')})`,+ );+ } else if (animation.totalDuration() > 0 || delay > 0) {+ problems.push(+ 'a wall-clock animation that is not attached to the provided timeline',+ );+ }+ }++ return problems;+};++const assertNoCallbacks = (value: unknown) => {+ const callbacks = findCallbacksInValue(value);+ if (callbacks.length > 0) {+ throw new Error(+ `useGsapTimeline does not allow timeline callbacks (${callbacks.join(', ')}). Derive visual state from the timeline instead of side effects.`,+ );+ }+};++type TimelineControls = {+ isPaused: () => boolean;+ pause: () => void;+ renderAt: (seconds: number) => void;+ restoreForContextRevert: () => void;+ kill: () => void;+};++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.+ const originalPaused = timeline.paused.bind(timeline);+ const originalTotalTime = timeline.totalTime.bind(timeline);+ const originalKill = timeline.kill.bind(timeline);++ const playbackError = () => {+ throw new Error(+ 'useGsapTimeline builders must not start playback. Remove play(), resume(), restart(), reverse(), or paused(false).',+ );+ };++ timeline.play = playbackError as typeof timeline.play;+ timeline.resume = playbackError as typeof timeline.resume;+ timeline.restart = playbackError as typeof timeline.restart;+ timeline.reverse = playbackError as typeof timeline.reverse;+ timeline.pause = (() => {+ throw new Error(+ 'useGsapTimeline owns timeline pause state. Do not call timeline.pause() inside the builder.',+ );+ }) as typeof timeline.pause;++ timeline.paused = ((value?: boolean) => {+ if (value === false) {+ return playbackError();+ }++ if (value !== undefined) {+ throw new Error(+ 'useGsapTimeline owns timeline pause state. Read timeline.paused() if needed, but do not set it.',+ );+ }++ return originalPaused();+ }) as typeof timeline.paused;++ const seekingError = () => {+ throw new Error(+ 'useGsapTimeline owns timeline seeking. Remove seek(), time(), totalTime(), progress(), totalProgress(), tweenTo(), or tweenFromTo() from the builder.',+ );+ };++ // 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()).+ for (const method of ['timeScale', 'duration', 'totalDuration'] as const) {+ const original = (timeline[method] as (...args: unknown[]) => unknown).bind(+ timeline,+ );+ (timeline as unknown as Record<string, unknown>)[method] = (+ ...args: unknown[]+ ) => {+ if (args.length > 0) {+ throw new Error(+ `useGsapTimeline does not support timeline.${method}(value). The Remotion frame drives the timeline at a fixed 1:1 time scale; author tween durations directly.`,+ );+ }++ return original();+ };+ }++ timeline.seek = seekingError as typeof timeline.seek;+ timeline.time = seekingError as typeof timeline.time;+ timeline.totalTime = seekingError as typeof timeline.totalTime;+ timeline.progress = seekingError as typeof timeline.progress;+ timeline.totalProgress = seekingError as typeof timeline.totalProgress;+ timeline.tweenTo = seekingError as typeof timeline.tweenTo;+ timeline.tweenFromTo = seekingError as typeof timeline.tweenFromTo;+ timeline.kill = (() => {+ throw new Error(+ 'useGsapTimeline owns timeline cleanup. Do not call timeline.kill() inside the builder.',+ );+ }) as typeof timeline.kill;++ const originalEventCallback = timeline.eventCallback.bind(timeline) as (+ ...args: unknown[]+ ) => unknown;+ timeline.eventCallback = ((...args: unknown[]) => {+ if (args.length > 1 && typeof args[1] === 'function') {+ throw new Error(+ 'useGsapTimeline does not allow timeline.eventCallback().',+ );+ }++ return originalEventCallback(...args);+ }) as typeof timeline.eventCallback;++ timeline.then = (() => {+ throw new Error(+ 'useGsapTimeline does not allow timeline.then() callbacks.',+ );+ }) as typeof timeline.then;++ const originalTo = timeline.to.bind(timeline);+ timeline.to = ((...args: Parameters<typeof timeline.to>) => {+ assertNoCallbacks(args[1]);+ return originalTo(...args);+ }) as typeof timeline.to;++ const originalFrom = timeline.from.bind(timeline);+ timeline.from = ((...args: Parameters<typeof timeline.from>) => {+ assertNoCallbacks(args[1]);+ return originalFrom(...args);+ }) as typeof timeline.from;++ const originalFromTo = timeline.fromTo.bind(timeline);+ timeline.fromTo = ((...args: Parameters<typeof timeline.fromTo>) => {+ assertNoCallbacks(args[1]);+ assertNoCallbacks(args[2]);+ return originalFromTo(...args);+ }) as typeof timeline.fromTo;++ const originalSet = timeline.set.bind(timeline);+ timeline.set = ((...args: Parameters<typeof timeline.set>) => {+ assertNoCallbacks(args[1]);+ return originalSet(...args);+ }) as typeof timeline.set;++ const originalAdd = timeline.add.bind(timeline);+ timeline.add = ((...args: Parameters<typeof timeline.add>) => {+ if (typeof args[0] === 'function') {+ throw new Error(+ 'useGsapTimeline does not allow callback functions in timeline.add().',+ );+ }++ return originalAdd(...args);+ }) as typeof timeline.add;++ timeline.call = (() => {+ throw new Error('useGsapTimeline does not allow timeline.call().');+ }) as typeof timeline.call;++ return {+ isPaused: () => originalPaused(),+ pause: () => {+ 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.+ 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.+ for (const method of [+ 'play',+ 'resume',+ 'restart',+ 'reverse',+ 'pause',+ 'paused',+ 'seek',+ 'time',+ 'totalTime',+ 'timeScale',+ 'duration',+ 'totalDuration',+ 'progress',+ 'totalProgress',+ 'tweenTo',+ 'tweenFromTo',+ 'kill',+ 'eventCallback',+ 'then',+ 'to',+ 'from',+ 'fromTo',+ 'set',+ 'add',+ 'call',+ ]) {+ delete (timeline as unknown as Record<string, unknown>)[method];+ }+ },+ kill: () => {+ originalKill();+ },+ };+};++/**+ * Builds one scoped, paused GSAP timeline and seeks it from Remotion's frame.+ * The hook never plays the timeline on GSAP's ticker.+ */+export const useGsapTimeline = <T extends Element>(+ build: GsapTimelineBuilder<T>,+ {dependencies = EMPTY_DEPENDENCIES}: UseGsapTimelineOptions = {},+): GsapScopeRef<T> => {+ const frame = useCurrentFrame();+ const {fps} = useVideoConfig();+ const scopeRef = useRef<T>(null);+ const controlsRef = useRef<TimelineControls | null>(null);+ const buildRef = useRef(build);+ const frameRef = useRef(frame);+ const fpsRef = useRef(fps);++ buildRef.current = build;+ frameRef.current = frame;+ fpsRef.current = fps;++ useLayoutEffect(() => {+ const scope = scopeRef.current;+ if (!scope) {+ return;+ }++ const state: {+ timeline: gsap.core.Timeline | null;+ controls: TimelineControls | null;+ } = {timeline: null, controls: null};+ const context = gsap.context(() => undefined, scope);++ try {+ context.add(() => {+ state.timeline = gsap.timeline({paused: true});+ state.controls = guardTimelineMethods(state.timeline);+ const selector = gsap.utils.selector(scope);++ const preexisting = new Set<gsap.core.Animation>(+ gsap.globalTimeline.getChildren(true, true, true),+ );+ const originalTickerAdd = gsap.ticker.add.bind(gsap.ticker);+ gsap.ticker.add = (() => {+ throw new Error(+ 'useGsapTimeline builders must not register gsap.ticker callbacks. The Remotion frame is the only clock.',+ );+ }) as typeof gsap.ticker.add;++ let result: unknown;+ try {+ result = buildRef.current({+ timeline: state.timeline,+ scope,+ selector,+ });+ } finally {+ gsap.ticker.add = originalTickerAdd;+ }++ if (!state.controls.isPaused()) {+ throw new Error(+ 'useGsapTimeline builders must not start playback. Remove play(), resume(), restart(), or reverse().',+ );+ }++ // 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]'), ...)`.+ if (result instanceof Promise) {+ throw new TypeError(+ 'useGsapTimeline builders must be synchronous. Load data before building the timeline.',+ );+ }++ const callbacks = findTimelineCallbacks(state.timeline);+ if (callbacks.length > 0) {+ throw new Error(+ `useGsapTimeline does not allow timeline callbacks (${callbacks.join(', ')}). Derive visual state from the timeline instead of side effects.`,+ );+ }++ const nonElementTargets = findNonElementTargets(state.timeline);+ if (nonElementTargets.length > 0) {+ throw new Error(+ `useGsapTimeline tweens must target DOM or SVG elements, but found: ${nonElementTargets.join(+ '; ',+ )}. Tweening plain objects animates in the Player but freezes in stills and renders, because nothing re-reads the object after a frame seek. Animate elements through the scoped selector or refs, or derive numeric values with Remotion's useCurrentFrame() and interpolate().`,+ );+ }++ const nondeterminism = findTimelineNondeterminism(state.timeline);+ if (nondeterminism.length > 0) {+ throw new Error(+ `useGsapTimeline rejects nondeterministic tween configuration (${nondeterminism.join(+ '; ',+ )}). GSAP resolves these with unseeded Math.random, so every mount and every render process disagrees. Derive stable values from data or Remotion's seeded random().`,+ );+ }++ const strays = findStrayAnimations(state.timeline, preexisting);+ if (strays.length > 0) {+ throw new Error(+ `useGsapTimeline builders created ${strays.join(+ '; ',+ )}. Animations that are not children of the provided timeline advance on the wall clock instead of the Remotion frame. Attach them to the timeline, or use a plain zero-duration gsap.set() for static state.`,+ );+ }++ // 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).+ const ownedTimeline = state.timeline;+ const startTimeOnOwnedClock = (child: gsap.core.Animation): number => {+ let time = child.startTime();+ let parent = child.parent as gsap.core.Timeline | null;+ while (parent && parent !== ownedTimeline) {+ time = parent.startTime() + time / (parent.timeScale() || 1);+ parent = parent.parent as gsap.core.Timeline | null;+ }++ return time;+ };++ const startTimes = [+ ...new Set(+ state.timeline+ .getChildren(true, true, true)+ .map((child) => startTimeOnOwnedClock(child))+ .filter((startTime) => Number.isFinite(startTime))+ .sort((a, b) => a - b),+ ),+ ];+ const totalDuration = state.timeline.totalDuration();+ const cycleDuration = state.timeline.duration();+ const primeEnd = Number.isFinite(totalDuration)+ ? totalDuration+ : Number.isFinite(cycleDuration)+ ? cycleDuration+ : 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;+ } catch (error) {+ state.controls?.restoreForContextRevert();+ context.revert();+ state.controls?.kill();+ throw error;+ }++ return () => {+ controlsRef.current = null;+ state.controls?.restoreForContextRevert();+ context.revert();+ state.controls?.kill();+ };+ // The explicit dependency list is the same contract as useEffect dependencies.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, dependencies);++ useLayoutEffect(() => {+ const controls = controlsRef.current;+ if (controls) {+ controls.renderAt(frameToSeconds(frame, fps));+ }+ }, [fps, frame]);++ return scopeRef;+};diff --git a/packages/gsap/tsconfig.json b/packages/gsap/tsconfig.jsonnew file mode 100644index 0000000000..22b60bbe95--- /dev/null+++ b/packages/gsap/tsconfig.json@@ -0,0 +1,16 @@+{+ "extends": "../tsconfig.settings.json",+ "compilerOptions": {+ "rootDir": "src",+ "outDir": "dist",+ "jsx": "react-jsx",+ "skipLibCheck": true,+ "target": "ES2022",+ "module": "es2020",+ "moduleResolution": "bundler",+ "declaration": true,+ "emitDeclarationOnly": true+ },+ "include": ["src"],+ "references": [{"path": "../core"}]+}diff --git a/packages/it-tests/package.json b/packages/it-tests/package.jsonindex 8f8947c912..ab5c7a23b1 100644--- a/packages/it-tests/package.json+++ b/packages/it-tests/package.json@@ -54,9 +54,12 @@"@remotion/transitions": "workspace:*","@remotion/webcodecs": "workspace:*","@rspack/core": "1.7.11",+ "@types/pngjs": "6.0.5","@types/sharp": "0.28.6","create-video": "workspace:*","execa": "5.1.1",+ "pixelmatch": "7.1.0",+ "pngjs": "7.0.0","postcss": "8.5.23","postcss-loader": "7.3.4","postcss-size": "5.0.0",diff --git a/packages/it-tests/src/rendering/gsap-render-parity.test.ts b/packages/it-tests/src/rendering/gsap-render-parity.test.tsnew file mode 100644index 0000000000..27ebf95913--- /dev/null+++ b/packages/it-tests/src/rendering/gsap-render-parity.test.ts@@ -0,0 +1,395 @@+import {afterAll, beforeAll, describe, expect, it} from 'bun:test';+import {availableParallelism} from 'node:os';+import path from 'node:path';+import {+ openBrowser,+ renderFrames,+ renderStill,+ selectComposition,+ type HeadlessBrowser,+} from '@remotion/renderer';+import execa from 'execa';+import pixelmatch from 'pixelmatch';+import {PNG} from 'pngjs';++const SHOWCASE_ID = 'gsap-showcase';+const FPS_24_FIXTURE_ID = 'gsap-fps-24';+const FPS_30_FIXTURE_ID = 'gsap-fps-30';+const FPS_60_FIXTURE_ID = 'gsap-fps-60';+const SEQUENCE_FIXTURE_ID = 'gsap-sequence';+const NESTED_SEQUENCE_FIXTURE_ID = 'gsap-nested-sequence';+const SURFACE_FIXTURE_ID = 'gsap-surface';+const OVERLAP_FIXTURE_ID = 'gsap-overlap';+const SAME_PROPERTY_OVERLAP_FIXTURE_ID = 'gsap-same-property-overlap';+const SVG_ROOT_FIXTURE_ID = 'gsap-svg-root';++const exampleDir = path.resolve(__dirname, '..', '..', '..', 'example');+const serveUrl = path.join(exampleDir, 'build');+const shuffledFrames = [105, 0, 195, 45, 150, 15, 75];+const rendererConcurrency = Math.min(8, availableParallelism());++// pixelmatch's types do not accept Buffer directly+const asUint8Array = (data: Buffer) =>+ new Uint8Array(data.buffer, data.byteOffset, data.byteLength);++const pixelDifference = (leftBuffer: Buffer, rightBuffer: Buffer) => {+ const left = PNG.sync.read(leftBuffer);+ const right = PNG.sync.read(rightBuffer);++ expect(right.width).toBe(left.width);+ expect(right.height).toBe(left.height);++ return pixelmatch(+ asUint8Array(left.data),+ asUint8Array(right.data),+ undefined,+ left.width,+ left.height,+ {threshold: 0},+ );+};++const pixelAt = (buffer: Buffer, x: number, y: number) => {+ const png = PNG.sync.read(buffer);+ const offset = (y * png.width + x) * 4;+ return [...png.data.subarray(offset, offset + 4)];+};++describe('GSAP renderer parity', () => {+ let composition: Awaited<ReturnType<typeof selectComposition>>;+ let browser: HeadlessBrowser;++ beforeAll(async () => {+ // In CI, the example project is already bundled.+ if (!process.env.CI) {+ await execa('bun', ['x', 'remotion', 'bundle'], {+ cwd: exampleDir,+ });+ }++ composition = await selectComposition({serveUrl, id: SHOWCASE_ID});+ browser = await openBrowser('chrome', {logLevel: 'warn'});+ });++ afterAll(async () => {+ await browser?.close({silent: false});+ });++ const renderFrameMap = async (+ targetComposition: Awaited<ReturnType<typeof selectComposition>>,+ concurrency: number,+ ) => {+ const frames = new Map<number, Buffer>();++ await renderFrames({+ serveUrl,+ composition: targetComposition,+ inputProps: {},+ outputDir: null,+ imageFormat: 'png',+ frameRange: [0, targetComposition.durationInFrames - 1],+ everyNthFrame: 1,+ concurrency,+ puppeteerInstance: browser,+ onStart: () => undefined,+ onFrameUpdate: () => undefined,+ onFrameBuffer: (buffer, frame) => frames.set(frame, buffer),+ logLevel: 'warn',+ });++ return frames;+ };++ it(+ 'matches concurrent sequence rendering with shuffled direct-frame rendering',+ async () => {+ const sequenceFrames = new Map<number, Buffer>();++ await renderFrames({+ serveUrl,+ composition,+ inputProps: {},+ outputDir: null,+ imageFormat: 'png',+ frameRange: [0, composition.durationInFrames - 1],+ everyNthFrame: 15,+ concurrency: Math.min(4, rendererConcurrency),+ puppeteerInstance: browser,+ onStart: () => undefined,+ onFrameUpdate: () => undefined,+ onFrameBuffer: (buffer, frame) => {+ sequenceFrames.set(frame, buffer);+ },+ logLevel: 'warn',+ });++ for (const frame of shuffledFrames) {+ const direct = await renderStill({+ serveUrl,+ composition,+ frame,+ output: null,+ imageFormat: 'png',+ puppeteerInstance: browser,+ logLevel: 'warn',+ });++ const fromSequence = sequenceFrames.get(frame);+ expect(+ fromSequence,+ `sequence buffer for frame ${frame}`,+ ).toBeDefined();+ expect(+ direct.buffer,+ `direct buffer for frame ${frame}`,+ ).not.toBeNull();+ const difference = pixelDifference(fromSequence!, direct.buffer!);+ expect(difference, `showcase frame ${frame}`).toBe(0);+ }+ },+ {timeout: 120000},+ );++ it(+ 'repeated direct renders of the same frame are pixel-identical',+ async () => {+ const first = await renderStill({+ serveUrl,+ composition,+ frame: 87,+ output: null,+ puppeteerInstance: browser,+ imageFormat: 'png',+ logLevel: 'warn',+ });+ const second = await renderStill({+ serveUrl,+ composition,+ frame: 87,+ output: null,+ puppeteerInstance: browser,+ imageFormat: 'png',+ logLevel: 'warn',+ });++ expect(pixelDifference(first.buffer!, second.buffer!)).toBe(0);+ },+ {timeout: 60000},+ );++ it(+ 'maps equal local time to equal pixels at 30fps, 60fps, and inside a Sequence',+ async () => {+ const fps24 = await selectComposition({serveUrl, id: FPS_24_FIXTURE_ID});+ const fps30 = await selectComposition({serveUrl, id: FPS_30_FIXTURE_ID});+ const fps60 = await selectComposition({serveUrl, id: FPS_60_FIXTURE_ID});+ const sequence = await selectComposition({+ serveUrl,+ id: SEQUENCE_FIXTURE_ID,+ });+ const nestedSequence = await selectComposition({+ serveUrl,+ id: NESTED_SEQUENCE_FIXTURE_ID,+ });++ const halfSecond24 = await renderStill({+ serveUrl,+ composition: fps24,+ frame: 12,+ output: null,+ puppeteerInstance: browser,+ imageFormat: 'png',+ logLevel: 'warn',+ });+ const halfSecond30 = await renderStill({+ serveUrl,+ composition: fps30,+ frame: 15,+ output: null,+ puppeteerInstance: browser,+ imageFormat: 'png',+ logLevel: 'warn',+ });+ const halfSecond60 = await renderStill({+ serveUrl,+ composition: fps60,+ frame: 30,+ output: null,+ puppeteerInstance: browser,+ imageFormat: 'png',+ logLevel: 'warn',+ });+ const halfSecondInSequence = await renderStill({+ serveUrl,+ composition: sequence,+ frame: 45,+ output: null,+ puppeteerInstance: browser,+ imageFormat: 'png',+ logLevel: 'warn',+ });+ const halfSecondInNestedSequence = await renderStill({+ serveUrl,+ composition: nestedSequence,+ frame: 45,+ output: null,+ puppeteerInstance: browser,+ imageFormat: 'png',+ logLevel: 'warn',+ });++ expect(pixelDifference(halfSecond24.buffer!, halfSecond30.buffer!)).toBe(+ 0,+ );+ expect(pixelDifference(halfSecond30.buffer!, halfSecond60.buffer!)).toBe(+ 0,+ );+ expect(+ pixelDifference(halfSecond30.buffer!, halfSecondInSequence.buffer!),+ ).toBe(0);+ expect(+ pixelDifference(+ halfSecond30.buffer!,+ halfSecondInNestedSequence.buffer!,+ ),+ ).toBe(0);+ },+ {timeout: 120000},+ );++ it(+ 'renders exact start, midpoint, and post-duration states',+ async () => {+ const fps30 = await selectComposition({serveUrl, id: FPS_30_FIXTURE_ID});+ const frames = await Promise.all(+ [0, 12, 59].map(async (frame) =>+ renderStill({+ serveUrl,+ composition: fps30,+ frame,+ output: null,+ puppeteerInstance: browser,+ imageFormat: 'png',+ logLevel: 'warn',+ }),+ ),+ );++ expect(pixelAt(frames[0]!.buffer!, 50, 50)).toEqual([0, 0, 0, 255]);+ expect(pixelAt(frames[1]!.buffer!, 50, 50)).toEqual([102, 0, 0, 255]);+ expect(pixelAt(frames[2]!.buffer!, 50, 50)).toEqual([255, 0, 0, 255]);+ },+ {timeout: 60000},+ );++ it(+ 'matches every complex-surface frame between serial and concurrent rendering',+ async () => {+ const surface = await selectComposition({+ serveUrl,+ id: SURFACE_FIXTURE_ID,+ });+ const serial = await renderFrameMap(surface, 1);+ const concurrent = await renderFrameMap(surface, rendererConcurrency);++ expect(serial.size).toBe(surface.durationInFrames);+ expect(concurrent.size).toBe(surface.durationInFrames);++ for (let frame = 0; frame < surface.durationInFrames; frame++) {+ expect(+ pixelDifference(serial.get(frame)!, concurrent.get(frame)!),+ `surface frame ${frame}`,+ ).toBe(0);+ }+ },+ {timeout: 240000},+ );++ it(+ 'keeps overlapping scoped Sequences deterministic under shuffled access',+ async () => {+ const overlap = await selectComposition({+ serveUrl,+ id: OVERLAP_FIXTURE_ID,+ });+ const rendered = await renderFrameMap(overlap, rendererConcurrency);++ for (const frame of [84, 30, 9, 64, 10, 45, 29]) {+ const direct = await renderStill({+ serveUrl,+ composition: overlap,+ frame,+ output: null,+ puppeteerInstance: browser,+ imageFormat: 'png',+ logLevel: 'warn',+ });++ expect(pixelDifference(rendered.get(frame)!, direct.buffer!)).toBe(0);+ }+ },+ {timeout: 240000},+ );++ it(+ 'keeps overlapping same-property tweens identical across stills, serial and concurrent renders',+ async () => {+ const contested = await selectComposition({+ serveUrl,+ id: SAME_PROPERTY_OVERLAP_FIXTURE_ID,+ });+ const serial = await renderFrameMap(contested, 1);+ const concurrent = await renderFrameMap(contested, rendererConcurrency);++ for (const frame of [23, 16, 44, 0, 59]) {+ const direct = await renderStill({+ serveUrl,+ composition: contested,+ frame,+ output: null,+ puppeteerInstance: browser,+ imageFormat: 'png',+ logLevel: 'warn',+ });++ expect(+ pixelDifference(serial.get(frame)!, direct.buffer!),+ `contested frame ${frame} still vs serial`,+ ).toBe(0);+ expect(+ pixelDifference(serial.get(frame)!, concurrent.get(frame)!),+ `contested frame ${frame} serial vs concurrent`,+ ).toBe(0);+ }+ },+ {timeout: 240000},+ );++ it(+ 'supports an SVG element as the timeline scope root',+ async () => {+ const svg = await selectComposition({serveUrl, id: SVG_ROOT_FIXTURE_ID});+ const direct = await renderStill({+ serveUrl,+ composition: svg,+ frame: 15,+ output: null,+ puppeteerInstance: browser,+ imageFormat: 'png',+ logLevel: 'warn',+ });+ const repeated = await renderStill({+ serveUrl,+ composition: svg,+ frame: 15,+ output: null,+ puppeteerInstance: browser,+ imageFormat: 'png',+ logLevel: 'warn',+ });++ expect(pixelDifference(direct.buffer!, repeated.buffer!)).toBe(0);+ },+ {timeout: 60000},+ );+});diff --git a/packages/studio-shared/src/package-info.ts b/packages/studio-shared/src/package-info.tsindex 24e83aedc1..31dbe12c73 100644--- a/packages/studio-shared/src/package-info.ts+++ b/packages/studio-shared/src/package-info.ts@@ -38,6 +38,7 @@ const allPackages = ['fonts','gif','google-fonts',+ 'gsap','install-whisper-cpp','it-tests','react18-tests',@@ -174,6 +175,7 @@ export const descriptions: {[key in Pkgs]: string | null} = {'install-whisper-cpp': 'Helpers for installing and using Whisper.cpp','whisper-web': 'Helpers for using Whisper.cpp in browser using WASM','google-fonts': 'Use Google Fonts in Remotion',+ gsap: 'Drive GSAP timelines from the Remotion frame',mcp: "Remotion's Model Context Protocol",'media-utils': 'Utilities for working with media files',lottie: 'Include Lottie animations in Remotion',@@ -306,6 +308,7 @@ export const installableMap: {[key in Pkgs]: boolean} = {fonts: true,gif: true,'google-fonts': true,+ gsap: true,'install-whisper-cpp': true,'whisper-web': true,'it-tests': false,@@ -407,6 +410,7 @@ export const apiDocs: {[key in Pkgs]: string | null} = {'install-whisper-cpp': 'https://www.remotion.dev/docs/install-whisper-cpp','whisper-web': 'https://www.remotion.dev/docs/whisper-web','google-fonts': 'https://www.remotion.dev/docs/google-fonts',+ gsap: 'https://www.remotion.dev/docs/gsap','media-utils': 'https://www.remotion.dev/docs/media-utils',lottie: 'https://www.remotion.dev/docs/lottie',licensing: 'https://www.remotion.dev/docs/licensing',diff --git a/tsconfig.json b/tsconfig.jsonindex 81aeabe508..ebf79be111 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -60,6 +60,9 @@{"path": "./packages/google-fonts"},+ {+ "path": "./packages/gsap"+ },{"path": "./packages/openai-whisper"},