🎥 Make videos programmatically with React
feat: per-segment easing arrays for interpolate()
JonnyBurgerf6b46b93f3fc
diff --git a/packages/animation-utils/src/transformation-helpers/interpolate-styles/index.tsx b/packages/animation-utils/src/transformation-helpers/interpolate-styles/index.tsxindex f29029a2cb..8ea0c37047 100644--- a/packages/animation-utils/src/transformation-helpers/interpolate-styles/index.tsx+++ b/packages/animation-utils/src/transformation-helpers/interpolate-styles/index.tsx@@ -1,5 +1,10 @@-import type {ExtrapolateType, InterpolateOptions} from 'remotion';-import {interpolate, interpolateColors} from 'remotion';+import {+ interpolate,+ interpolateColors,+ type EasingFunction,+ type ExtrapolateType,+ type InterpolateOptions,+} from 'remotion';import type {CSSPropertiesKey,CSSPropertiesValue,@@ -8,6 +13,38 @@ import type {} from '../../type';import {breakDownValueIntoUnitNumberAndFunctions} from './utils';+type InterpolateStylesResolvedOptions = {+ easing: EasingFunction;+ extrapolateLeft: ExtrapolateType;+ extrapolateRight: ExtrapolateType;+};++function assertInterpolateStylesEasingOption(+ easing: EasingFunction | readonly EasingFunction[] | undefined,+ inputRangeLength: number,+) {+ if (easing === undefined) {+ return;+ }++ if (typeof easing === 'function') {+ return;+ }++ const expectedLength = inputRangeLength - 1;+ if (easing.length !== expectedLength) {+ throw new Error(+ `When easing is an array, it must have one entry per segment between keyframes (length inputRange.length - 1 = ${expectedLength}), but got length ${easing.length}`,+ );+ }++ for (let i = 0; i < easing.length; i++) {+ if (typeof easing[i] !== 'function') {+ throw new Error(`easing[${i}] must be a function`);+ }+ }+}+const interpolatedPropertyPart = ({inputValue,inputRange,@@ -23,7 +60,7 @@ const interpolatedPropertyPart = ({finalStylePropertyPart: UnitNumberAndFunction;initialStyleProperty: CSSPropertiesValue;finalStyleProperty: CSSPropertiesValue;- options: Required<InterpolateOptions>;+ options: InterpolateStylesResolvedOptions;}): string | number => {if (finalStylePropertyPart === undefined) {throw new TypeError(@@ -129,7 +166,7 @@ const interpolateProperty = ({inputRange: number[];initialStyleProperty: CSSPropertiesValue;finalStyleProperty: CSSPropertiesValue;- options: Required<InterpolateOptions>;+ options: InterpolateStylesResolvedOptions;}) => {if (typeof initialStyleProperty !== typeof finalStyleProperty &&@@ -180,7 +217,7 @@ const interpolateStylesFunction = ({inputRange: number[];initialStyle: Style;finalStyle: Style;- options: Required<InterpolateOptions>;+ options: InterpolateStylesResolvedOptions;}): Style => {const [startingValue, endingValue] = inputRange;return Object.keys(initialStyle).reduce((acc, key) => {@@ -305,7 +342,15 @@ export const interpolateStyles = (const initialStyle = outputStylesRange[startIndex];const finalStyle = outputStylesRange[endIndex];- const easing = options?.easing ?? ((num: number): number => num);+ assertInterpolateStylesEasingOption(options?.easing, inputRange.length);++ const easingOption = options?.easing;+ const segmentEasing: EasingFunction =+ easingOption === undefined+ ? (num: number): number => num+ : typeof easingOption === 'function'+ ? easingOption+ : easingOption[startIndex];const extrapolateLeft: ExtrapolateType = options?.extrapolateLeft ?? 'extend';const extrapolateRight: ExtrapolateType =@@ -317,7 +362,7 @@ export const interpolateStyles = (initialStyle,finalStyle,options: {- easing,+ easing: segmentEasing,extrapolateLeft,extrapolateRight,},diff --git a/packages/core/src/interpolate.ts b/packages/core/src/interpolate.tsindex 78f075a2ee..c193855db5 100644--- a/packages/core/src/interpolate.ts+++ b/packages/core/src/interpolate.ts@@ -10,16 +10,22 @@ export type ExtrapolateType = 'extend' | 'identity' | 'clamp' | 'wrap';export type EasingFunction = (input: number) => number;export type InterpolateOptions = Partial<{- easing: EasingFunction;+ easing: EasingFunction | readonly EasingFunction[];extrapolateLeft: ExtrapolateType;extrapolateRight: ExtrapolateType;}>;+type InterpolateSegmentResolvedOptions = {+ easing: EasingFunction;+ extrapolateLeft: ExtrapolateType;+ extrapolateRight: ExtrapolateType;+};+function interpolateFunction(input: number,inputRange: [number, number],outputRange: [number, number],- options: Required<InterpolateOptions>,+ options: InterpolateSegmentResolvedOptions,): number {const {extrapolateLeft, extrapolateRight, easing} = options;@@ -114,6 +120,32 @@ function checkInfiniteRange(name: string, arr: readonly number[]) {}}+function checkValidEasingOption(+ easing: EasingFunction | readonly EasingFunction[] | undefined,+ inputRangeLength: number,+) {+ if (easing === undefined) {+ return;+ }++ if (typeof easing === 'function') {+ return;+ }++ const expectedLength = inputRangeLength - 1;+ if (easing.length !== expectedLength) {+ throw new Error(+ `When easing is an array, it must have one entry per segment between keyframes (length inputRange.length - 1 = ${expectedLength}), but got length ${easing.length}`,+ );+ }++ for (let i = 0; i < easing.length; i++) {+ if (typeof easing[i] !== 'function') {+ throw new Error(`easing[${i}] must be a function`);+ }+ }+}+/** @description Allows you to map a range of values to another using a concise syntax.* @see [Documentation](https://remotion.dev/docs/interpolate)@@ -151,7 +183,21 @@ export function interpolate(checkValidInputRange(inputRange);- const easing = options?.easing ?? ((num: number): number => num);+ checkValidEasingOption(options?.easing, inputRange.length);++ const easingOption = options?.easing;+ const defaultEasing = (num: number): number => num;+ const resolveEasingForSegment = (segmentIndex: number): EasingFunction => {+ if (easingOption === undefined) {+ return defaultEasing;+ }++ if (typeof easingOption === 'function') {+ return easingOption;+ }++ return easingOption[segmentIndex] as EasingFunction;+ };let extrapolateLeft: ExtrapolateType = 'extend';if (options?.extrapolateLeft !== undefined) {@@ -173,7 +219,7 @@ export function interpolate([inputRange[range], inputRange[range + 1]],[outputRange[range], outputRange[range + 1]],{- easing,+ easing: resolveEasingForSegment(range),extrapolateLeft,extrapolateRight,},diff --git a/packages/core/src/test/interpolate.test.ts b/packages/core/src/test/interpolate.test.tsindex 7b228ca631..d3ee22f748 100644--- a/packages/core/src/test/interpolate.test.ts+++ b/packages/core/src/test/interpolate.test.ts@@ -101,6 +101,70 @@ test('Easing test', () => {).toEqual(1 - Math.cos((0.5 * Math.PI) / 2));});+test('Easing array: one easing per segment between keyframes', () => {+ const linear = (t: number) => t;+ const quad = (t: number) => t * t;+ // Midpoint of second segment [10, 20]: normalized t = 0.5, quad -> 0.25+ expect(+ interpolate(15, [0, 10, 20], [0, 10, 20], {+ easing: [linear, quad],+ }),+ ).toEqual(12.5);+});++test('Easing array: first segment easing only affects first segment', () => {+ const linear = (t: number) => t;+ const quad = (t: number) => t * t;+ expect(+ interpolate(5, [0, 10, 20], [0, 10, 20], {+ easing: [quad, linear],+ }),+ ).toEqual(2.5);+});++test('Easing array: same as single easing when all segments use the same function', () => {+ const single = interpolate(15, [0, 10, 20], [0, 100, 200], {+ easing: Easing.linear,+ });+ const arrayed = interpolate(15, [0, 10, 20], [0, 100, 200], {+ easing: [Easing.linear, Easing.linear],+ });+ expect(arrayed).toEqual(single);+});++test('Easing array must have length inputRange.length - 1', () => {+ expectToThrow(() => {+ interpolate(1, [0, 10, 20], [0, 1, 2], {+ easing: [Easing.linear],+ });+ }, /When easing is an array, it must have one entry per segment between keyframes \(length inputRange.length - 1 = 2\), but got length 1/);+});++test('Easing array entries must be functions', () => {+ expectToThrow(() => {+ interpolate(5, [0, 10, 20], [0, 10, 20], {+ // @ts-expect-error+ easing: [Easing.linear, 'not-a-fn'],+ });+ }, /easing\[1\] must be a function/);+});++test('Easing array with two keyframes uses a single easing entry', () => {+ expect(+ interpolate(0.5, [0, 1], [0, 1], {+ easing: [Easing.sin],+ }),+ ).toEqual(1 - Math.cos((0.5 * Math.PI) / 2));+});++test('Easing array with two keyframes rejects more than one entry', () => {+ expectToThrow(() => {+ interpolate(0.5, [0, 1], [0, 1], {+ easing: [Easing.linear, Easing.linear],+ });+ }, /When easing is an array, it must have one entry per segment between keyframes \(length inputRange.length - 1 = 1\), but got length 2/);+});+test('Easing.circle with default extrapolate extend clamps normalized input', () => {expect(interpolate(150, [0, 100], [0, 100], {diff --git a/packages/docs/docs/animation-utils/interpolate-styles.mdx b/packages/docs/docs/animation-utils/interpolate-styles.mdxindex b286561b4f..e0e75e2ae1 100644--- a/packages/docs/docs/animation-utils/interpolate-styles.mdx+++ b/packages/docs/docs/animation-utils/interpolate-styles.mdx@@ -41,7 +41,7 @@ A function that takes 3-4 arguments:1. The input value.2. The range of values that you expect the input to assume.3. The range of output styles that you want the input to map to.-4. Options object, same as the options of [`interpolate()`](/docs/interpolate#extrapolateleft). Optional.+4. Options object with the same keys as [`interpolate()`](/docs/interpolate#easing) (`extrapolateLeft`, `extrapolateRight`, `easing`). Optional.## Return valuediff --git a/packages/docs/docs/interpolate.mdx b/packages/docs/docs/interpolate.mdxindex 6a11706aca..6fc22a8713 100644--- a/packages/docs/docs/interpolate.mdx+++ b/packages/docs/docs/interpolate.mdx@@ -150,7 +150,7 @@ interpolate(1.5, [0, 1], [0, 2], {extrapolateRight: 'wrap'}); // 1_Default_: `(x) => x`-Function which allows you to customize the input, for example to apply a certain easing function.+Pass a single function to customize the normalized progress within the **active segment** (between two adjacent keyframes), for example to apply an easing curve.By default, the input is left unmodified, resulting in a pure linear interpolation. [Read the documentation for the built-in easing functions](/docs/easing).```ts twoslash@@ -165,7 +165,6 @@ interpolate(frame, [0, 100], [0, 1], {extrapolateRight: 'clamp',});-//this is Remotion2.0 featureinterpolate(frame, [0, 10, 40, 100], [0, 0.2, 0.6, 1], {easing: Easing.bezier(0.8, 0.22, 0.96, 0.65),extrapolateLeft: 'clamp',@@ -173,6 +172,21 @@ interpolate(frame, [0, 10, 40, 100], [0, 0.2, 0.6, 1], {});```+#### Per-segment easing (array)<AvailableFrom v="4.0.462" />++You can pass an array of easing functions with **one entry per segment** between consecutive keyframes. Its length must be `inputRange.length - 1` (the same as `outputRange.length - 1`). The first easing applies between the first and second keyframe, the second easing between the second and third, and so on.++```ts twoslash+import {useCurrentFrame} from 'remotion';+const frame = useCurrentFrame();+// ---cut---+import {interpolate, Easing} from 'remotion';++interpolate(frame, [0, 100, 200], [0, 1, 2], {+ easing: [Easing.bezier(0, 0, 1, 1), Easing.bezier(0, 0, 1, 1)],+});+```+## TypesSince `v3.3.77`, types for the options are exported from Remotion.