Skip to content

🎥 Make videos programmatically with React

Add new package animation utils

ChetanKarwa0ac117689fa0
diff --git a/packages/animation-utils/.eslintrc b/packages/animation-utils/.eslintrc
new file mode 100644
index 0000000000..3ad72802a8
--- /dev/null
+++ b/packages/animation-utils/.eslintrc
@@ -0,0 +1,3 @@
+{
+ "extends": "@remotion"
+}
diff --git a/packages/animation-utils/LICENSE.md b/packages/animation-utils/LICENSE.md
new file mode 100644
index 0000000000..663c50a7e4
--- /dev/null
+++ b/packages/animation-utils/LICENSE.md
@@ -0,0 +1,7 @@
+Copyright 2023 Chetan Karwa
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/packages/animation-utils/README.md b/packages/animation-utils/README.md
new file mode 100644
index 0000000000..a95308f25d
--- /dev/null
+++ b/packages/animation-utils/README.md
@@ -0,0 +1,25 @@
+## `@remotion/animation-utils`
+
+A React hook for use with [Remotion](https://remotion.dev/) that returns the current second.
+
+### Usage
+
+```tsx
+import { useCurrentSecond } from "@remotion/animation-utils";
+import { AbsoluteFill } from "remotion";
+
+export const Example: React.FC = () => {
+ const second = useCurrentSecond();
+
+ return (
+ <AbsoluteFill>
+ <h1>Second: {second}</h1>
+ </AbsoluteFill>
+ );
+};
+```
+
+## License
+
+See the [LICENSE.md](LICENSE.md) file for the license of this repo.
+To use Remotion, a company license is needed for some entities. [Read the terms here](https://github.com/remotion-dev/remotion/blob/main/LICENSE.md).
diff --git a/packages/animation-utils/package-lock.json b/packages/animation-utils/package-lock.json
new file mode 100644
index 0000000000..ad93e56518
--- /dev/null
+++ b/packages/animation-utils/package-lock.json
@@ -0,0 +1,106 @@
+{
+ "name": "@remotion/animation-utils",
+ "version": "0.0.1",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@remotion/animation-utils",
+ "version": "0.0.1",
+ "devDependencies": {
+ "remotion": "^4.0.46"
+ },
+ "peerDependencies": {
+ "react": "^18.2.0",
+ "react-dom": "^18.2.0",
+ "remotion": "*"
+ }
+ },
+ "../../node_modules/.pnpm/[email protected][email protected][email protected]/node_modules/remotion": {
+ "version": "4.0.46",
+ "dev": true,
+ "license": "SEE LICENSE IN LICENSE.md",
+ "devDependencies": {
+ "@jonny/eslint-config": "3.0.273",
+ "@rollup/plugin-typescript": "^8.2.0",
+ "@testing-library/react": "14.0.0",
+ "@types/node": "18.14.6",
+ "@types/react": "18.0.26",
+ "@types/react-dom": "18.0.10",
+ "@vitejs/plugin-react": "^2.0.0",
+ "eslint": "8.42.0",
+ "eslint-plugin-require-extensions": "^0.1.2",
+ "jsdom": "21.1.0",
+ "prettier": "3.0.2",
+ "prettier-plugin-organize-imports": "^3.2.2",
+ "react": "^18.0.0",
+ "react-dom": "^18.0.0",
+ "rimraf": "^3.0.2",
+ "rollup": "^2.70.1",
+ "vitest": "0.31.1",
+ "webpack": "5.83.1",
+ "zod": "3.22.3"
+ },
+ "peerDependencies": {
+ "react": ">=16.8.0",
+ "react-dom": ">=16.8.0"
+ }
+ },
+ "node_modules/js-tokens": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
+ "peer": true
+ },
+ "node_modules/loose-envify": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
+ "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
+ "peer": true,
+ "dependencies": {
+ "js-tokens": "^3.0.0 || ^4.0.0"
+ },
+ "bin": {
+ "loose-envify": "cli.js"
+ }
+ },
+ "node_modules/react": {
+ "version": "18.2.0",
+ "resolved": "https://registry.npmjs.org/react/-/react-18.2.0.tgz",
+ "integrity": "sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==",
+ "peer": true,
+ "dependencies": {
+ "loose-envify": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/react-dom": {
+ "version": "18.2.0",
+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.2.0.tgz",
+ "integrity": "sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==",
+ "peer": true,
+ "dependencies": {
+ "loose-envify": "^1.1.0",
+ "scheduler": "^0.23.0"
+ },
+ "peerDependencies": {
+ "react": "^18.2.0"
+ }
+ },
+ "node_modules/remotion": {
+ "resolved": "../../node_modules/.pnpm/[email protected][email protected][email protected]/node_modules/remotion",
+ "link": true
+ },
+ "node_modules/scheduler": {
+ "version": "0.23.0",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.0.tgz",
+ "integrity": "sha512-CtuThmgHNg7zIZWAXi3AsyIzA3n4xx7aNyjwC2VJldO2LMVDhFK+63xGqq6CsJH4rTAt6/M+N4GhZiDYPx9eUw==",
+ "peer": true,
+ "dependencies": {
+ "loose-envify": "^1.1.0"
+ }
+ }
+ }
+}
diff --git a/packages/animation-utils/package.json b/packages/animation-utils/package.json
new file mode 100644
index 0000000000..3902a003fe
--- /dev/null
+++ b/packages/animation-utils/package.json
@@ -0,0 +1,34 @@
+{
+ "name": "@remotion/animation-utils",
+ "author": {
+ "name": "Chetan Karwa",
+ "email": "[email protected]"
+ },
+ "version": "4.0.84",
+ "description": "A set of animation utilities for Remotion",
+ "main": "./dist/index.js",
+ "module": "./dist/index.mjs",
+ "types": "./dist/index.d.ts",
+ "scripts": {
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
+ "formatting": "prettier src --check",
+ "lint": "eslint src --ext ts,tsx",
+ "watch": "tsc -w",
+ "build": "tsc -d"
+ },
+ "dependencies": {
+ "remotion": "workspace:*"
+ },
+ "peerDependencies": {
+ "react": ">=16.8.0",
+ "react-dom": ">=16.8.0"
+ },
+ "devDependencies": {
+ "@types/react": "18.0.26",
+ "@types/react-dom": "^18.2.11",
+ "remotion": "^4.0.46"
+ },
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/packages/animation-utils/src/index.ts b/packages/animation-utils/src/index.ts
new file mode 100644
index 0000000000..383c2914c8
--- /dev/null
+++ b/packages/animation-utils/src/index.ts
@@ -0,0 +1,10 @@
+export * from "./transformation-helpers/make-transform";
+export * from "./transformation-helpers/use-interpolate-styles";
+
+export type {
+ LengthUnit,
+ LengthPercentageUnit,
+ AngleUnit,
+ TransformFunction,
+ TransformFunctionReturnType,
+} from "./type";
diff --git a/packages/animation-utils/src/transformation-helpers/make-transform/index.ts b/packages/animation-utils/src/transformation-helpers/make-transform/index.ts
new file mode 100644
index 0000000000..81a32355d6
--- /dev/null
+++ b/packages/animation-utils/src/transformation-helpers/make-transform/index.ts
@@ -0,0 +1,54 @@
+import { TransformFunctionReturnType } from "../../type";
+import {
+ matrix,
+ matrix3d,
+ perspective,
+ rotate,
+ rotate3d,
+ rotateX,
+ rotateY,
+ rotateZ,
+ scale,
+ scale3d,
+ scaleX,
+ scaleY,
+ scaleZ,
+ skew,
+ skewX,
+ skewY,
+ translate,
+ translate3d,
+ translateX,
+ translateY,
+ translateZ,
+} from "./transform-functions";
+
+export function makeTransform(
+ transforms: TransformFunctionReturnType[]
+): string {
+ return transforms.map((transform) => transform()).join(" ");
+}
+
+export {
+ matrix,
+ matrix3d,
+ perspective,
+ rotate,
+ rotate3d,
+ rotateX,
+ rotateY,
+ rotateZ,
+ scale,
+ scale3d,
+ scaleX,
+ scaleY,
+ scaleZ,
+ skew,
+ skewX,
+ skewY,
+ translate,
+ translate3d,
+ translateX,
+ translateY,
+ translateZ,
+};
diff --git a/packages/animation-utils/src/transformation-helpers/make-transform/transform-functions.ts b/packages/animation-utils/src/transformation-helpers/make-transform/transform-functions.ts
new file mode 100644
index 0000000000..c53f65f273
--- /dev/null
+++ b/packages/animation-utils/src/transformation-helpers/make-transform/transform-functions.ts
@@ -0,0 +1,184 @@
+/* eslint-disable max-params */
+
+import {
+ TransformFunction,
+ LengthUnit,
+ LengthPercentageUnit,
+ AngleUnit,
+} from "../../type";
+
+/* Matrix transformation */
+
+function matrix(
+ a: number,
+ b: number,
+ c: number,
+ d: number,
+ tx: number,
+ ty: number
+): TransformFunction {
+ return () => `matrix(${a}, ${b}, ${c}, ${d}, ${tx}, ${ty})`;
+}
+
+function matrix3d(
+ a1: number,
+ b1: number,
+ c1: number,
+ d1: number,
+ a2: number,
+ b2: number,
+ c2: number,
+ d2: number,
+ a3: number,
+ b3: number,
+ c3: number,
+ d3: number,
+ a4: number,
+ b4: number,
+ c4: number,
+ d4: number
+): TransformFunction {
+ return () =>
+ `matrix3d(${a1}, ${b1}, ${c1}, ${d1}, ${a2}, ${b2}, ${c2}, ${d2}, ${a3}, ${b3}, ${c3}, ${d3}, ${a4}, ${b4}, ${c4}, ${d4})`;
+}
+
+/* Perspective */
+
+function perspective(
+ length: number,
+ unit: LengthUnit = "px"
+): TransformFunction {
+ return () => `perspective(${length}${unit})`;
+}
+
+/* Rotation */
+
+function rotate(angle: number, unit: AngleUnit = "deg"): TransformFunction {
+ return () => `rotate(${angle}${unit})`;
+}
+
+function rotate3d(
+ x: number,
+ y: number,
+ z: number,
+ angle: number,
+ unit: AngleUnit = "deg"
+): TransformFunction {
+ return () => `rotate3d(${x}, ${y}, ${z}, ${angle}${unit})`;
+}
+
+function rotateX(angle: number, unit: AngleUnit = "deg"): TransformFunction {
+ return () => `rotateX(${angle}${unit})`;
+}
+
+function rotateY(angle: number, unit: AngleUnit = "deg"): TransformFunction {
+ return () => `rotateY(${angle}${unit})`;
+}
+
+function rotateZ(angle: number, unit: AngleUnit = "deg"): TransformFunction {
+ return () => `rotateZ(${angle}${unit})`;
+}
+
+/* Scale */
+
+function scale(x: number, y: number = x): TransformFunction {
+ return () => `scale(${x}, ${y})`;
+}
+
+function scale3d(x: number, y: number, z: number): TransformFunction {
+ return () => `scale3d(${x}, ${y}, ${z})`;
+}
+
+function scaleX(x: number): TransformFunction {
+ return () => `scaleX(${x})`;
+}
+
+function scaleY(y: number): TransformFunction {
+ return () => `scaleY(${y})`;
+}
+
+function scaleZ(z: number): TransformFunction {
+ return () => `scaleZ(${z})`;
+}
+
+/* Skew */
+
+function skew(
+ x: number,
+ y: number = x,
+ unit: AngleUnit = "deg"
+): TransformFunction {
+ return () => `skew(${x}${unit}, ${y}${unit})`;
+}
+
+function skewX(angle: number, unit: AngleUnit = "deg"): TransformFunction {
+ return () => `skewX(${angle}${unit})`;
+}
+
+function skewY(angle: number, unit: AngleUnit = "deg"): TransformFunction {
+ return () => `skewY(${angle}${unit})`;
+}
+
+/* Translation */
+
+function translate(
+ x: number,
+ y = 0,
+ unitX: LengthPercentageUnit = "px",
+ unitY: LengthPercentageUnit = unitX
+): TransformFunction {
+ return () => `translate(${x}${unitX}, ${y}${unitY})`;
+}
+
+function translate3d(
+ x: number,
+ y: number,
+ z: number,
+ unitX: LengthPercentageUnit = "px",
+ unitY: LengthPercentageUnit = unitX,
+ unitZ: LengthUnit = "px"
+): TransformFunction {
+ return () => `translate3d(${x}${unitX}, ${y}${unitY}, ${z}${unitZ})`;
+}
+
+function translateX(
+ x: number,
+ unit: LengthPercentageUnit = "px"
+): TransformFunction {
+ return () => `translateX(${x}${unit})`;
+}
+
+function translateY(
+ y: number,
+ unit: LengthPercentageUnit = "px"
+): TransformFunction {
+ return () => `translateY(${y}${unit})`;
+}
+
+function translateZ(z: number, unit: LengthUnit = "px"): TransformFunction {
+ return () => `translateZ(${z}${unit})`;
+}
+
+export {
+ matrix,
+ matrix3d,
+ perspective,
+ rotate,
+ rotate3d,
+ rotateX,
+ rotateY,
+ rotateZ,
+ scale,
+ scale3d,
+ scaleX,
+ scaleY,
+ scaleZ,
+ skew,
+ skewX,
+ skewY,
+ translate,
+ translate3d,
+ translateX,
+ translateY,
+ translateZ,
+};
diff --git a/packages/animation-utils/src/transformation-helpers/use-interpolate-styles/constants.ts b/packages/animation-utils/src/transformation-helpers/use-interpolate-styles/constants.ts
new file mode 100644
index 0000000000..0c24163b43
--- /dev/null
+++ b/packages/animation-utils/src/transformation-helpers/use-interpolate-styles/constants.ts
@@ -0,0 +1,157 @@
+const NUMBER = "[-+]?\\d*\\.?\\d+";
+const PERCENTAGE = NUMBER + "%";
+
+const STANDARD_COLOR_NAMES = [
+ "transparent",
+ "aliceblue",
+ "antiquewhite",
+ "aqua",
+ "aquamarine",
+ "azure",
+ "beige",
+ "bisque",
+ "black",
+ "blanchedalmond",
+ "blue",
+ "blueviolet",
+ "brown",
+ "burlywood",
+ "burntsienna",
+ "cadetblue",
+ "chartreuse",
+ "chocolate",
+ "coral",
+ "cornflowerblue",
+ "cornsilk",
+ "crimson",
+ "cyan",
+ "darkblue",
+ "darkcyan",
+ "darkgoldenrod",
+ "darkgray",
+ "darkgreen",
+ "darkgrey",
+ "darkkhaki",
+ "darkmagenta",
+ "darkolivegreen",
+ "darkorange",
+ "darkorchid",
+ "darkred",
+ "darksalmon",
+ "darkseagreen",
+ "darkslateblue",
+ "darkslategray",
+ "darkslategrey",
+ "darkturquoise",
+ "darkviolet",
+ "deeppink",
+ "deepskyblue",
+ "dimgray",
+ "dimgrey",
+ "dodgerblue",
+ "firebrick",
+ "floralwhite",
+ "forestgreen",
+ "fuchsia",
+ "gainsboro",
+ "ghostwhite",
+ "gold",
+ "goldenrod",
+ "gray",
+ "green",
+ "greenyellow",
+ "grey",
+ "honeydew",
+ "hotpink",
+ "indianred",
+ "indigo",
+ "ivory",
+ "khaki",
+ "lavender",
+ "lavenderblush",
+ "lawngreen",
+ "lemonchiffon",
+ "lightblue",
+ "lightcoral",
+ "lightcyan",
+ "lightgoldenrodyellow",
+ "lightgray",
+ "lightgreen",
+ "lightgrey",
+ "lightpink",
+ "lightsalmon",
+ "lightseagreen",
+ "lightskyblue",
+ "lightslategray",
+ "lightslategrey",
+ "lightsteelblue",
+ "lightyellow",
+ "lime",
+ "limegreen",
+ "linen",
+ "magenta",
+ "maroon",
+ "mediumaquamarine",
+ "mediumblue",
+ "mediumorchid",
+ "mediumpurple",
+ "mediumseagreen",
+ "mediumslateblue",
+ "mediumspringgreen",
+ "mediumturquoise",
+ "mediumvioletred",
+ "midnightblue",
+ "mintcream",
+ "mistyrose",
+ "moccasin",
+ "navajowhite",
+ "navy",
+ "oldlace",
+ "olive",
+ "olivedrab",
+ "orange",
+ "orangered",
+ "orchid",
+ "palegoldenrod",
+ "palegreen",
+ "paleturquoise",
+ "palevioletred",
+ "papayawhip",
+ "peachpuff",
+ "peru",
+ "pink",
+ "plum",
+ "powderblue",
+ "purple",
+ "rebeccapurple",
+ "red",
+ "rosybrown",
+ "royalblue",
+ "saddlebrown",
+ "salmon",
+ "sandybrown",
+ "seagreen",
+ "seashell",
+ "sienna",
+ "silver",
+ "skyblue",
+ "slateblue",
+ "slategray",
+ "slategrey",
+ "snow",
+ "springgreen",
+ "steelblue",
+ "tan",
+ "teal",
+ "thistle",
+ "tomato",
+ "turquoise",
+ "violet",
+ "wheat",
+ "white",
+ "whitesmoke",
+ "yellow",
+ "yellowgreen",
+];
+
+export { NUMBER, PERCENTAGE, STANDARD_COLOR_NAMES };
diff --git a/packages/animation-utils/src/transformation-helpers/use-interpolate-styles/index.tsx b/packages/animation-utils/src/transformation-helpers/use-interpolate-styles/index.tsx
new file mode 100644
index 0000000000..328ad23f75
--- /dev/null
+++ b/packages/animation-utils/src/transformation-helpers/use-interpolate-styles/index.tsx
@@ -0,0 +1,222 @@
+import { useState, useEffect, useMemo } from "react";
+import {
+ useCurrentFrame,
+ useVideoConfig,
+ interpolate,
+ interpolateColors,
+} from "remotion";
+import { breakDownValueIntoUnitNumberAndFunctions } from "./utils";
+import {
+ CSSPropertiesKey,
+ CSSPropertiesValue,
+ InterpolateStylesParams,
+ Style,
+ UnitNumberAndFunction,
+} from "../../type";
+
+const getInterpolatedPartValue = (
+ currentFrame: number,
+ inputRange: number[],
+ startValuePart: UnitNumberAndFunction,
+ endValuePart: UnitNumberAndFunction,
+ startValue: CSSPropertiesValue,
+ endValue: CSSPropertiesValue
+): string => {
+ if (endValuePart === undefined) {
+ throw new TypeError(
+ `The start and end values must be of the same type. Start value: ${startValue}, end value: ${endValue}`
+ );
+ }
+ if (startValuePart.color) {
+ if (!endValuePart.color) {
+ throw new TypeError(
+ `The start and end values must be of the same type. Start value: ${startValue}, end value: ${endValue}`
+ );
+ }
+ const interpolatedColor = interpolateColors(currentFrame, inputRange, [
+ startValuePart.color,
+ endValuePart.color as string,
+ ]);
+ return `${interpolatedColor}`;
+ }
+ if (startValuePart.function) {
+ if (
+ !endValuePart?.function ||
+ startValuePart.function.name !== endValuePart.function?.name
+ ) {
+ throw new TypeError(
+ `The start and end values must be of the same type. Start value: ${startValue}, end value: ${endValue}`
+ );
+ }
+ const endValuePartFunction = endValuePart.function;
+ const endValuePartFunctionArgs = endValuePartFunction.values || [];
+ const interpolatedFunctionArgs = startValuePart.function.values.reduce(
+ (acc: string, startValuePartFunctionArg, index) => {
+ const endValuePartFunctionArg = endValuePartFunctionArgs[index];
+ const interpolatedArg = getInterpolatedPartValue(
+ currentFrame,
+ inputRange,
+ startValuePartFunctionArg,
+ endValuePartFunctionArg,
+ startValue,
+ endValue
+ );
+ return `${acc}, ${interpolatedArg}`;
+ },
+ ""
+ );
+ return `${startValuePart.function.name}(${interpolatedFunctionArgs.slice(
+ 2
+ )})`;
+ }
+
+ if (typeof startValuePart.number === "undefined") {
+ return `${startValuePart.unit}`;
+ }
+ if (startValuePart.unit !== endValuePart.unit) {
+ throw new TypeError(
+ `The units of the start and end values must match. Start value: ${startValue}, end value: ${endValue}`
+ );
+ }
+ const startNumber = startValuePart.number;
+ const endNumber = endValuePart.number || 0;
+ const interpolatedNumber = interpolate(currentFrame, inputRange, [
+ startNumber,
+ endNumber,
+ ]);
+ const interpolatedUnit = startValuePart.unit;
+ return `${interpolatedNumber}${interpolatedUnit}`;
+};
+
+const getInterpolatedPropertyValue = (
+ currentFrame: number,
+ inputRange: number[],
+ startValue: CSSPropertiesValue,
+ endValue: CSSPropertiesValue
+) => {
+ if (typeof startValue !== typeof endValue) {
+ return startValue;
+ }
+ if (typeof startValue === "number") {
+ return interpolate(currentFrame, inputRange, [
+ startValue,
+ endValue as number,
+ ]);
+ }
+
+ const startValueParts = breakDownValueIntoUnitNumberAndFunctions(startValue);
+ const endValueArray = breakDownValueIntoUnitNumberAndFunctions(endValue);
+
+ const interpolatedValue = startValueParts.reduce(
+ (acc, startValuePart, index) => {
+ const interpolatedValuePart = getInterpolatedPartValue(
+ currentFrame,
+ inputRange,
+ startValuePart,
+ endValueArray[index],
+ startValue,
+ endValue
+ );
+ return `${acc} ${interpolatedValuePart}`;
+ },
+ ""
+ );
+ return interpolatedValue.slice(1);
+};
+
+const interpolateStyles = (
+ frame: number,
+ [startFrame, endFrame]: number[],
+ startStyle: Style,
+ endStyle: Style
+): Style => {
+ const interpolatedStyle = Object.keys(startStyle).reduce((acc, key) => {
+ const interpolatedValue = getInterpolatedPropertyValue(
+ frame,
+ [startFrame, endFrame],
+ startStyle[key as CSSPropertiesKey],
+ endStyle[key as CSSPropertiesKey]
+ );
+ return {
+ ...acc,
+ [key]: interpolatedValue,
+ };
+ }, {});
+ return interpolatedStyle;
+};
+
+export const useInterpolateStyles = ({
+ inputRangeInFrames,
+ inputRangeInSeconds,
+ outputStyles,
+}: InterpolateStylesParams) => {
+ useEffect(() => {
+ console.log("rerendering because of inputRangeInFrames");
+ }, [inputRangeInFrames]);
+ useEffect(() => {
+ console.log("rerendering because of inputRangeInSeconds");
+ }, [inputRangeInSeconds]);
+ useEffect(() => {
+ console.log("rerendering because of outputStyles");
+ }, [outputStyles]);
+ const [currentStyles, setCurrentStyles] = useState<Style>({});
+ const [areInputsValid, setAreInputsValid] = useState(false);
+ const frame = useCurrentFrame();
+ const { fps } = useVideoConfig();
+
+ const interpolateFrameSteps = useMemo(
+ () =>
+ inputRangeInFrames ||
+ inputRangeInSeconds?.map((duration) => Math.round(duration * fps)) ||
+ [],
+ [fps, inputRangeInFrames, inputRangeInSeconds]
+ );
+
+ useEffect(() => {
+ if (interpolateFrameSteps.length !== outputStyles.length) {
+ throw new TypeError(
+ `The number of steps in the interpolation must match the number of output styles.`
+ );
+ } else if (interpolateFrameSteps.length < 2) {
+ throw new TypeError(
+ `The number of steps in the interpolation must be at least 2.`
+ );
+ } else {
+ setAreInputsValid(true);
+ }
+ }, [interpolateFrameSteps, outputStyles]);
+
+ useEffect(() => {
+ const updateCurrentStyles = () => {
+ if (!areInputsValid) {
+ return outputStyles[0] || {};
+ }
+ if (frame < interpolateFrameSteps[0]) {
+ setCurrentStyles(outputStyles[0]);
+ return;
+ }
+ if (frame >= interpolateFrameSteps[interpolateFrameSteps.length - 1]) {
+ setCurrentStyles(outputStyles[outputStyles.length - 1]);
+ return;
+ }
+
+ const startIndex =
+ interpolateFrameSteps.findIndex((step) => frame < step) - 1;
+ const endIndex = startIndex + 1;
+ const startFrame = interpolateFrameSteps[startIndex];
+ const endFrame = interpolateFrameSteps[endIndex];
+ const startStyle = outputStyles[startIndex];
+ const endStyle = outputStyles[endIndex];
+ const currentFrameStyles = interpolateStyles(
+ frame,
+ [startFrame, endFrame],
+ startStyle,
+ endStyle
+ );
+ setCurrentStyles(currentFrameStyles);
+ };
+ updateCurrentStyles();
+ }, [areInputsValid, frame, interpolateFrameSteps, outputStyles]);
+
+ return currentStyles;
+};
diff --git a/packages/animation-utils/src/transformation-helpers/use-interpolate-styles/utils.ts b/packages/animation-utils/src/transformation-helpers/use-interpolate-styles/utils.ts
new file mode 100644
index 0000000000..7d562bbbae
--- /dev/null
+++ b/packages/animation-utils/src/transformation-helpers/use-interpolate-styles/utils.ts
@@ -0,0 +1,159 @@
+import { CSSPropertiesValue, ColorMatchers } from "../../type";
+import { NUMBER, PERCENTAGE, STANDARD_COLOR_NAMES } from "./constants";
+
+function call(...args: unknown[]): string {
+ return "\\(\\s*(" + args.join(")\\s*,\\s*(") + ")\\s*\\)";
+}
+
+function getColorMatchers(): ColorMatchers {
+ const cachedMatchers: ColorMatchers = {
+ rgb: undefined,
+ rgba: undefined,
+ hsl: undefined,
+ hsla: undefined,
+ hex3: undefined,
+ hex4: undefined,
+ hex5: undefined,
+ hex6: undefined,
+ hex8: undefined,
+ };
+ if (cachedMatchers.rgb === undefined) {
+ cachedMatchers.rgb = new RegExp("rgb" + call(NUMBER, NUMBER, NUMBER));
+ cachedMatchers.rgba = new RegExp(
+ "rgba" + call(NUMBER, NUMBER, NUMBER, NUMBER)
+ );
+ cachedMatchers.hsl = new RegExp(
+ "hsl" + call(NUMBER, PERCENTAGE, PERCENTAGE)
+ );
+ cachedMatchers.hsla = new RegExp(
+ "hsla" + call(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER)
+ );
+ cachedMatchers.hex3 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
+ cachedMatchers.hex4 =
+ /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
+ cachedMatchers.hex6 = /^#([0-9a-fA-F]{6})$/;
+ cachedMatchers.hex8 = /^#([0-9a-fA-F]{8})$/;
+ }
+
+ return cachedMatchers;
+}
+
+const extractOrderedPartsOfValue = (value: string) => {
+ const parts = [];
+ let remainingValue = value;
+
+ while (remainingValue.length > 0) {
+ const functionMatch = remainingValue.match(/([a-zA-Z-]+)\(([^)]+)\)/);
+
+ // If there's a function, add it to the parts and remove it from the remaining value
+ if (functionMatch) {
+ const { index } = functionMatch;
+ const matchedFunction = functionMatch[0];
+
+ // Add any parts before the function
+ if ((index || 0) > 0) {
+ parts.push(...remainingValue.substring(0, index).trim().split(/\s+/));
+ }
+
+ parts.push(matchedFunction);
+
+ remainingValue = remainingValue.substring(
+ (index || 0) + matchedFunction.length
+ );
+ } else {
+ // If there's no function, add the remaining value to the parts
+ parts.push(...remainingValue.trim().split(/\s+/));
+ break;
+ }
+ }
+
+ return parts.filter((part) => part !== ""); // Filter out any empty strings
+};
+
+const classifyArgsOfFunction = (value: string) => {
+ let nestedLevel = 0;
+ const values = [];
+ let currentValue = "";
+
+ for (const char of value) {
+ if (char === "(") nestedLevel++;
+ else if (char === ")") nestedLevel--;
+
+ if (char === "," && nestedLevel === 0) {
+ values.push(currentValue.trim());
+ currentValue = "";
+ } else {
+ currentValue += char;
+ }
+ }
+ if (currentValue) values.push(currentValue.trim());
+
+ // Classify each value
+ return values.map((val) => {
+ const numberUnitMatch = val.match(/^(\d+(?:\.\d+)?)([a-zA-Z%]*)$/);
+ if (numberUnitMatch) {
+ const number = parseFloat(numberUnitMatch[1]);
+ const unit = numberUnitMatch[2];
+ return unit ? { number, unit } : { number };
+ }
+ return { unit: val };
+ });
+};
+
+const isColorValue = (value: string) => {
+ if (STANDARD_COLOR_NAMES.includes(value)) {
+ return true;
+ }
+ const matchers = getColorMatchers();
+ return (
+ matchers.rgb?.test(value) ||
+ matchers.rgba?.test(value) ||
+ matchers.hsl?.test(value) ||
+ matchers.hsla?.test(value) ||
+ matchers.hex3?.test(value) ||
+ matchers.hex4?.test(value) ||
+ matchers.hex5?.test(value) ||
+ matchers.hex6?.test(value) ||
+ matchers.hex8?.test(value)
+ );
+};
+
+const classifyParts = (parts: string[]) => {
+ return parts.map((part) => {
+ // Check for a color value like 'red', 'rgba(0, 0, 0, 0)', '#fff', etc.
+ if (isColorValue(part)) {
+ return { color: part };
+ }
+
+ // Check for a function like 'translateX(10px)' or 'rotate(90deg)'
+ const functionMatch = part.match(/([a-zA-Z-]+)\(([^)]+)\)/);
+ if (functionMatch) {
+ const functionName = functionMatch[1];
+ const functionValues = classifyArgsOfFunction(functionMatch[2]);
+ return { function: { name: functionName, values: functionValues } };
+ }
+
+ // Check for a number possibly followed by a unit
+ const numberUnitMatch = part.match(/^(\d+(?:\.\d+)?)([a-zA-Z%]*)$/);
+ if (numberUnitMatch) {
+ const number = parseFloat(numberUnitMatch[1]);
+ const unit = numberUnitMatch[2];
+ return unit ? { number, unit } : { number };
+ }
+
+ // If neither, treat as a unit (like 'solid', 'none', etc.)
+ return { unit: part };
+ });
+};
+
+const breakDownValueIntoUnitNumberAndFunctions = (
+ value: CSSPropertiesValue
+) => {
+ if (typeof value !== "string") {
+ return [];
+ }
+ const valueParts = extractOrderedPartsOfValue(value);
+ return classifyParts(valueParts);
+};
+
+export { getColorMatchers, breakDownValueIntoUnitNumberAndFunctions };
diff --git a/packages/animation-utils/src/type.ts b/packages/animation-utils/src/type.ts
new file mode 100644
index 0000000000..2c066f8d32
--- /dev/null
+++ b/packages/animation-utils/src/type.ts
@@ -0,0 +1,132 @@
+import {
+ matrix,
+ matrix3d,
+ perspective,
+ rotate,
+ rotate3d,
+ rotateX,
+ rotateY,
+ rotateZ,
+ scale,
+ scale3d,
+ scaleX,
+ scaleY,
+ scaleZ,
+ skew,
+ skewX,
+ skewY,
+ translate,
+ translate3d,
+ translateX,
+ translateY,
+ translateZ,
+} from "./transformation-helpers/make-transform";
+import { breakDownValueIntoUnitNumberAndFunctions } from "./transformation-helpers/use-interpolate-styles/utils";
+
+type TransformFunction = () => string;
+type LengthUnit =
+ | "cap"
+ | "ch"
+ | "em"
+ | "ex"
+ | "ic"
+ | "lh"
+ | "rem"
+ | "rlh"
+ | "vh"
+ | "vw"
+ | "vmax"
+ | "vmin"
+ | "vb"
+ | "vi"
+ | "cqw"
+ | "cqh"
+ | "cqi"
+ | "cqb"
+ | "cqmin"
+ | "cqmax"
+ | "px"
+ | "cm"
+ | "mm"
+ | "Q"
+ | "in"
+ | "pc"
+ | "pt";
+
+type LengthPercentageUnit = LengthUnit | "%";
+
+type AngleUnit = "deg" | "grad" | "rad" | "turn";
+
+type TransformFunctionReturnType = ReturnType<
+ | typeof matrix
+ | typeof matrix3d
+ | typeof perspective
+ | typeof rotate
+ | typeof rotate3d
+ | typeof rotateX
+ | typeof rotateY
+ | typeof rotateZ
+ | typeof scale
+ | typeof scale3d
+ | typeof scaleX
+ | typeof scaleY
+ | typeof scaleZ
+ | typeof skew
+ | typeof skewX
+ | typeof skewY
+ | typeof translate
+ | typeof translate3d
+ | typeof translateX
+ | typeof translateY
+ | typeof translateZ
+>;
+
+type MatcherType = RegExp | undefined;
+
+type ColorMatchers = {
+ rgb: MatcherType;
+ rgba: MatcherType;
+ hsl: MatcherType;
+ hsla: MatcherType;
+ hex3: MatcherType;
+ hex4: MatcherType;
+ hex5: MatcherType;
+ hex6: MatcherType;
+ hex8: MatcherType;
+};
+
+type Style = React.CSSProperties;
+type CSSPropertiesKey = keyof Style;
+type CSSPropertiesValue = Style[CSSPropertiesKey];
+
+type InterpolateStylesParams =
+ | {
+ inputRangeInFrames: number[];
+ inputRangeInSeconds?: number[];
+ outputStyles: Style[];
+ }
+ | {
+ inputRangeInFrames?: number[];
+ inputRangeInSeconds: number[];
+ outputStyles: Style[];
+ };
+
+type UnitNumberAndFunctions = ReturnType<
+ typeof breakDownValueIntoUnitNumberAndFunctions
+>;
+
+type UnitNumberAndFunction = UnitNumberAndFunctions[0];
+
+export type {
+ TransformFunction,
+ LengthUnit,
+ LengthPercentageUnit,
+ AngleUnit,
+ TransformFunctionReturnType,
+ ColorMatchers,
+ Style,
+ CSSPropertiesKey,
+ CSSPropertiesValue,
+ InterpolateStylesParams,
+ UnitNumberAndFunction,
+};
diff --git a/packages/animation-utils/tsconfig.json b/packages/animation-utils/tsconfig.json
new file mode 100644
index 0000000000..861a42175f
--- /dev/null
+++ b/packages/animation-utils/tsconfig.json
@@ -0,0 +1,9 @@
+{
+ "extends": "../tsconfig.settings.json",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "dist"
+ },
+ "include": ["src"],
+ "references": [{ "path": "../core" }]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3c8ddf6c55..21a4ca240c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -19,6 +19,25 @@ importers:
specifier: 18.14.6
version: 18.14.6
+ packages/animation-utils:
+ dependencies:
+ react:
+ specifier: ^18.2.0
+ version: 18.2.0
+ react-dom:
+ specifier: ^18.2.0
+ version: 18.2.0([email protected])
+ remotion:
+ specifier: workspace:*
+ version: link:../core
+ devDependencies:
+ '@types/react':
+ specifier: ^18.2.26
+ version: 18.2.47
+ '@types/react-dom':
+ specifier: ^18.2.11
+ version: 18.2.18
+
packages/astro-example:
dependencies:
'@astrojs/react':
@@ -6475,7 +6494,7 @@ packages:
'@docusaurus/react-loadable': 5.5.2([email protected])
'@docusaurus/types': 2.4.1(@swc/[email protected])([email protected])([email protected])
'@types/history': 4.7.11
- '@types/react': 18.0.26
+ '@types/react': 18.2.47
'@types/react-router-config': 5.0.6
'@types/react-router-dom': 5.3.1
react: 18.2.0
@@ -6813,7 +6832,7 @@ packages:
peerDependencies:
react: '*'
dependencies:
- '@types/react': 18.0.26
+ '@types/react': 18.2.47
prop-types: 15.8.1
react: 18.2.0
dev: false
@@ -6884,7 +6903,7 @@ packages:
'@docusaurus/utils': 2.4.1(@docusaurus/[email protected])(@swc/[email protected])
'@docusaurus/utils-common': 2.4.1(@docusaurus/[email protected])
'@types/history': 4.7.11
- '@types/react': 18.0.38
+ '@types/react': 18.2.47
'@types/react-router-config': 5.0.6
clsx: 1.2.1
parse-numeric-range: 1.3.0
@@ -6972,7 +6991,7 @@ packages:
react-dom: ^16.8.4 || ^17.0.0
dependencies:
'@types/history': 4.7.11
- '@types/react': 18.0.38
+ '@types/react': 18.2.47
commander: 5.1.0
joi: 17.6.0
react: 18.2.0
@@ -7846,7 +7865,7 @@ packages:
react: '>=16'
dependencies:
'@types/mdx': 2.0.5
- '@types/react': 18.0.38
+ '@types/react': 18.2.47
react: 18.2.0
dev: false
@@ -8967,7 +8986,7 @@ packages:
dependencies:
'@babel/runtime': 7.17.9
'@testing-library/dom': 8.16.0
- '@types/react-dom': 18.0.11
+ '@types/react-dom': 18.2.18
react: 18.2.0
react-dom: 18.2.0([email protected])
dev: true
@@ -8981,7 +9000,7 @@ packages:
dependencies:
'@babel/runtime': 7.17.9
'@testing-library/dom': 8.16.0
- '@types/react-dom': 18.0.11
+ '@types/react-dom': 18.2.18
react: 18.2.0
react-dom: 18.2.0([email protected])
dev: true
@@ -8995,7 +9014,7 @@ packages:
dependencies:
'@babel/runtime': 7.19.0
'@testing-library/dom': 8.16.0
- '@types/react-dom': 18.0.11
+ '@types/react-dom': 18.2.18
react: 18.2.0
react-dom: 18.2.0([email protected])
dev: true
@@ -9009,7 +9028,7 @@ packages:
dependencies:
'@babel/runtime': 7.19.0
'@testing-library/dom': 9.0.0
- '@types/react-dom': 18.0.11
+ '@types/react-dom': 18.2.18
react: 18.2.0
react-dom: 18.2.0([email protected])
dev: true
@@ -9241,7 +9260,7 @@ packages:
resolution: {integrity: sha512-iMIqiko6ooLrTh1joXodJK5X9xeEALT1kM5G3ZLhD3hszxBdIEd5C75U834D9mLcINgD4OyZf5uQXjkuYydWvA==}
dependencies:
- '@types/react': 18.0.26
+ '@types/react': 18.2.47
hoist-non-react-statics: 3.3.2
dev: false
@@ -9429,35 +9448,41 @@ packages:
resolution: {integrity: sha512-O38bPbI2CWtgw/OoQoY+BRelw7uysmXbWvw3nLWO21H1HSh+GOlqPuXshJfjmpNlKiiSDG9cc1JZAaMmVdcTlw==}
dependencies:
- '@types/react': 18.0.26
+ '@types/react': 18.2.47
+
+ resolution: {integrity: sha512-TJxDm6OfAX2KJWJdMEVTwWke5Sc/E/RlnPGvGfS0W7+6ocy2xhDVQVh/KvC2Uf7kACs+gDytdusDSdWfWkaNzw==}
+ dependencies:
+ '@types/react': 18.2.47
+ dev: true
resolution: {integrity: sha512-AVdWv4B8/++T5QQdnpveb2OVqD+0i8SOoT63ZRD+lNtQIYxzDak91V0k6olthy+H261d4t/MRBC1cfX1Rwsb6A==}
dependencies:
- '@types/react': 18.0.26
+ '@types/react': 18.2.47
dev: true
resolution: {integrity: sha512-bdx4aIBkQRDAnzc23JBFeZmVpmfLJHfHikmQukEt9qs4bQtq9f+PDbNwhR9u74FkIUyIDz1I1qJ8OF6RwadKpw==}
dependencies:
- '@types/react': 18.0.26
+ '@types/react': 18.2.47
dev: true
resolution: {integrity: sha512-mBDYl8x+oyPX/VBb3E638N0B7xG+SPk/EAMcVPeexqus/5aTpTphQi0curhhshOqRrc9t6OPoJfEUkbymse/lQ==}
dependencies:
- '@types/react': 18.0.26
+ '@types/react': 18.2.47
resolution: {integrity: sha512-5cjk9ottZAj7eaTsqzPUIlrVbh3hBAO2YaEL1rkjHKB3xNAId7oU8GhzvAX+gfmlfoxTwJnBjPxEHyxkEA1Ffg==}
dependencies:
- '@types/react': 18.0.26
+ '@types/react': 18.2.47
resolution: {integrity: sha512-db1mx37a1EJDf1XeX8jJN7R3PZABmJQXR8r28yUjVMFSjkmnQo6X6pOEEmNl+Tp2gYQOGPdYbFIipBtdElZ3Yg==}
dependencies:
'@types/history': 4.7.11
- '@types/react': 18.0.26
+ '@types/react': 18.2.47
'@types/react-router': 5.1.17
dev: false
@@ -9465,7 +9490,7 @@ packages:
resolution: {integrity: sha512-UvyRy73318QI83haXlaMwmklHHzV9hjl3u71MmM6wYNu0hOVk9NLTa0vGukf8zXUqnwz4O06ig876YSPpeK28A==}
dependencies:
'@types/history': 4.7.11
- '@types/react': 18.0.26
+ '@types/react': 18.2.47
'@types/react-router': 5.1.17
dev: false
@@ -9473,7 +9498,7 @@ packages:
resolution: {integrity: sha512-RNSXOyb3VyRs/EOGmjBhhGKTbnN6fHWvy5FNLzWfOWOGjgVUKqJZXfpKzLmgoU8h6Hj8mpALj/mbXQASOb92wQ==}
dependencies:
'@types/history': 4.7.11
- '@types/react': 18.0.26
+ '@types/react': 18.2.47
dev: false
@@ -9483,13 +9508,12 @@ packages:
'@types/scheduler': 0.16.2
csstype: 3.1.1
- resolution: {integrity: sha512-ExsidLLSzYj4cvaQjGnQCk4HFfVT9+EZ9XZsQ8Hsrcn8QNgXtpZ3m9vSIC2MWtx7jHictK6wYhQgGh6ic58oOw==}
+ resolution: {integrity: sha512-xquNkkOirwyCgoClNk85BjP+aqnIS+ckAJ8i37gAbDs14jfW/J23f2GItAf33oiUPQnqNMALiFeoM9Y5mbjpVQ==}
dependencies:
'@types/prop-types': 15.7.4
'@types/scheduler': 0.16.2
csstype: 3.1.1
- dev: false
resolution: {integrity: sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==}
@@ -9566,7 +9590,7 @@ packages:
resolution: {integrity: sha512-KuKJ9Z6xb93uJiIyxo/+ksS7yLjS1KzG6iv5i78dhVg/X3u5t1H7juRWqVmodIdz6wGVaIApo1u01kmFRdJHVw==}
dependencies:
'@types/hoist-non-react-statics': 3.3.1
- '@types/react': 18.0.38
+ '@types/react': 18.2.47
csstype: 3.1.1
dev: false
diff --git a/tsconfig.json b/tsconfig.json
index eab6b015ac..597a84104f 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -71,6 +71,9 @@
{
"path": "./packages/media-utils"
},
+ {
+ "path": "./packages/animation-utils"
+ },
{
"path": "./packages/motion-blur"
},