🎥 Make videos programmatically with React
remotion: Add easing to interpolateColors (#8240)
Jonny Burger95f935b3fe57
diff --git a/packages/core/src/interpolate-colors.ts b/packages/core/src/interpolate-colors.tsindex 173e1449c1..10ce5a315b 100644--- a/packages/core/src/interpolate-colors.ts+++ b/packages/core/src/interpolate-colors.ts@@ -3,11 +3,12 @@* https://github.com/software-mansion/react-native-reanimated/blob/master/src/reanimated2/Colors.ts*/-import {interpolate} from './interpolate.js';+import {interpolate, type InterpolateOptions} from './interpolate.js';-export type InterpolateColorsOptions = {- posterize: number | undefined;-};+export type InterpolateColorsOptions = Pick<+ InterpolateOptions,+ 'easing' | 'posterize'+>;type MatcherType = RegExp | undefined;@@ -671,6 +672,7 @@ const interpolateColorsRGB = (inputRange,colors.map((c) => f(c)),{+ easing: options?.easing,extrapolateLeft: 'clamp',extrapolateRight: 'clamp',posterize: options?.posterize,diff --git a/packages/core/src/interpolate-keyframed-status.ts b/packages/core/src/interpolate-keyframed-status.tsindex 6949736262..abcd91e1fc 100644--- a/packages/core/src/interpolate-keyframed-status.ts+++ b/packages/core/src/interpolate-keyframed-status.ts@@ -49,6 +49,7 @@ export const interpolateKeyframedStatus = ({try {return interpolateColors(frame, inputRange, outputs as string[], {+ easing: easing.map(easingToFn),posterize: status.posterize,});} catch {diff --git a/packages/core/src/test/interpolate-keyframed-status.test.ts b/packages/core/src/test/interpolate-keyframed-status.test.tsindex 2700119e59..8631e1776a 100644--- a/packages/core/src/test/interpolate-keyframed-status.test.ts+++ b/packages/core/src/test/interpolate-keyframed-status.test.ts@@ -126,6 +126,24 @@ test('interpolates colors', () => {expect(result).toMatch(/^rgba?\(/);});+test('interpolates color keyframes with easing', () => {+ const result = interpolateKeyframedStatus({+ frame: 30,+ status: {+ status: 'keyframed',+ interpolationFunction: 'interpolateColors',+ keyframes: [+ {frame: 0, value: 'black'},+ {frame: 60, value: 'white'},+ ],+ easing: [[0.42, 0, 1, 1]],+ clamping: {left: 'clamp', right: 'clamp'},+ posterize: undefined,+ },+ });+ expect(result).toBe('rgba(80, 80, 80, 1)');+});+test('posterizes the frame before interpolating color keyframes', () => {const result = interpolateKeyframedStatus({frame: 17,diff --git a/packages/core/src/test/interpolateColors.test.ts b/packages/core/src/test/interpolateColors.test.tsindex f573683ddd..7a7feac317 100644--- a/packages/core/src/test/interpolateColors.test.ts+++ b/packages/core/src/test/interpolateColors.test.ts@@ -1,4 +1,5 @@import {describe, expect, test} from 'bun:test';+import {Easing} from '../easing.js';import {interpolateColors} from '../interpolate-colors.js';import {expectToThrow} from './expect-to-throw.js';@@ -58,6 +59,30 @@ test('Posterize option must be a positive finite number for colors', () => {}, /posterize must be a positive finite number, but got 0/);});+test('Easing remaps color interpolation', () => {+ expect(+ interpolateColors(0.5, [0, 1], ['black', 'white'], {+ easing: (input) => input * input,+ }),+ ).toBe('rgba(64, 64, 64, 1)');+});++test('Easing array remaps color interpolation per segment', () => {+ expect(+ interpolateColors(15, [0, 10, 20], ['black', 'red', 'white'], {+ easing: [Easing.linear, (input) => input * input],+ }),+ ).toBe('rgba(255, 64, 64, 1)');+});++test('Easing array must have one entry per color segment', () => {+ expectToThrow(() => {+ interpolateColors(5, [0, 10, 20], ['black', 'red', 'white'], {+ easing: [Easing.linear],+ });+ }, /When easing is an array, it must have one entry per segment between keyframes/);+});+test('Can interpolate a single color keyframe', () => {expect(interpolateColors(-10, [20], ['blue'])).toBe('rgba(0, 0, 255, 1)');expect(interpolateColors(20, [20], ['blue'])).toBe('rgba(0, 0, 255, 1)');diff --git a/packages/docs/docs/interpolate-colors.mdx b/packages/docs/docs/interpolate-colors.mdxindex 0c07787a7a..2786d5934d 100644--- a/packages/docs/docs/interpolate-colors.mdx+++ b/packages/docs/docs/interpolate-colors.mdx@@ -22,6 +22,37 @@ Takes three to four arguments:With one color, `interpolateColors()` always returns the only output color as an `rgba` string.Single-color ranges are supported from <AvailableFrom v="4.0.469" inline />.+### easing<AvailableFrom v="4.0.475" />++_Default_: `Easing.linear`++Allows you to adjust the rate of the color interpolation.++```ts twoslash title="MyComposition.tsx"+import {Easing, interpolateColors, useCurrentFrame} from 'remotion';++const frame = useCurrentFrame();+const color = interpolateColors(frame, [0, 60], ['black', 'white'], {+ easing: Easing.in(Easing.quad),+});+```++When `inputRange` contains more than two values, you may pass one easing function per segment:++```ts twoslash title="MyComposition.tsx"+import {Easing, interpolateColors, useCurrentFrame} from 'remotion';++const frame = useCurrentFrame();+const color = interpolateColors(+ frame,+ [0, 30, 60],+ ['black', 'red', 'white'],+ {+ easing: [Easing.in(Easing.quad), Easing.out(Easing.quad)],+ },+);+```+## ReturnsA `rgba` color string. eg: `rgba(255, 100, 12, 1)`diff --git a/packages/studio-server/src/codemods/effect-param-expression.ts b/packages/studio-server/src/codemods/effect-param-expression.tsindex 3bae8dd7cc..9e32c74357 100644--- a/packages/studio-server/src/codemods/effect-param-expression.ts+++ b/packages/studio-server/src/codemods/effect-param-expression.ts@@ -25,12 +25,7 @@ const isNonLinearEasing = (const keyframedParamNeedsEasingImport = (param: EffectClipboardKeyframedParam,-) => {- return (- param.interpolationFunction !== 'interpolateColors' &&- param.easing.some(isNonLinearEasing)- );-};+) => param.easing.some(isNonLinearEasing);export const getRequiredRemotionImportsForEffectParams = (params: Iterable<EffectClipboardParam>,@@ -127,20 +122,20 @@ const makeKeyframedOptions = ({) as ObjectProperty,);}+ }- if (keyframedParamNeedsEasingImport(param)) {- const easingLocalName = remotionLocalNames.Easing ?? 'Easing';- properties.push(- b.objectProperty(- b.identifier('easing'),- b.arrayExpression(- param.easing.map((easing) =>- makeEasingExpression({easing, easingLocalName}),- ) as never,- ),- ) as ObjectProperty,- );- }+ if (keyframedParamNeedsEasingImport(param)) {+ const easingLocalName = remotionLocalNames.Easing ?? 'Easing';+ properties.push(+ b.objectProperty(+ b.identifier('easing'),+ b.arrayExpression(+ param.easing.map((easing) =>+ makeEasingExpression({easing, easingLocalName}),+ ) as never,+ ),+ ) as ObjectProperty,+ );}if (param.posterize !== undefined) {diff --git a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.tsindex b405f06a86..e6ae4c02eb 100644--- a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts+++ b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts@@ -696,12 +696,6 @@ const updateKeyframeEasing = ({throw new Error('Cannot update easing on non-keyframed value');}- const calleeName =- existing.callee.type === 'Identifier' ? existing.callee.name : null;- if (calleeName === 'interpolateColors') {- throw new Error('Cannot update easing on color keyframes');- }-const segmentCount = Math.max(0, existing.keyframes.length - 1);if (!Number.isInteger(segmentIndex) ||diff --git a/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts b/packages/studio-server/src/preview-server/routes/can-update-sequence-props.tsindex d755f4fbb9..52c3b4f6f4 100644--- a/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts+++ b/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts@@ -332,10 +332,6 @@ const getInterpolationMetadata = (const value = property.value as Expression;if (key === 'easing') {- if (interpolationFunction === 'interpolateColors') {- return null;- }-const parsedEasing = getKeyframeEasingArray({easingNode: value,segments,diff --git a/packages/studio-server/src/test/compute-sequence-props-status.test.ts b/packages/studio-server/src/test/compute-sequence-props-status.test.tsindex 5ae90b1b1e..f4ee0f158f 100644--- a/packages/studio-server/src/test/compute-sequence-props-status.test.ts+++ b/packages/studio-server/src/test/compute-sequence-props-status.test.ts@@ -93,6 +93,41 @@ export const Example: React.FC = () => {});});+test('computeSequencePropsStatus should return easing for interpolated color props', () => {+ const input = `import React from 'react';+import {Easing, Solid, interpolateColors, useCurrentFrame} from 'remotion';++export const Example: React.FC = () => {+\tconst frame = useCurrentFrame();+\treturn (+\t\t<Solid color={interpolateColors(frame, [0, 100, 200], ['red', 'green', 'blue'], {easing: [Easing.bezier(0.42, 0, 1, 1), Easing.linear], posterize: 2})} width={100} height={100} />+\t);+};+`;+ const result = computeSequencePropsStatusFromContent({+ fileContents: input,+ nodePath: getNodePathFromContent(input, 7),+ keys: ['color'],+ effects: [],+ });++ expect(result.canUpdate).toBe(true);+ if (!result.canUpdate) throw new Error('Expected canUpdate to be true');++ expect(result.props.color).toEqual({+ status: 'keyframed',+ interpolationFunction: 'interpolateColors',+ keyframes: [+ {frame: 0, value: 'red'},+ {frame: 100, value: 'green'},+ {frame: 200, value: 'blue'},+ ],+ easing: [[0.42, 0, 1, 1], 'linear'],+ clamping: {left: 'clamp', right: 'clamp'},+ posterize: 2,+ });+});+test('computeSequencePropsStatus should return keyframes for interpolated translate props', () => {const input = `import React from 'react';import {Sequence, interpolate, useCurrentFrame} from 'remotion';diff --git a/packages/studio-server/src/test/paste-effects.test.ts b/packages/studio-server/src/test/paste-effects.test.tsindex 94e185c8de..a574aa5469 100644--- a/packages/studio-server/src/test/paste-effects.test.ts+++ b/packages/studio-server/src/test/paste-effects.test.ts@@ -280,7 +280,7 @@ test('pasteEffects replaces existing effects with mixed static and keyframed par{frame: 0, value: 'red'},{frame: 100, value: 'green'},],- easing: ['linear'],+ easing: [[0.1, 0.2, 0.3, 0.4]],clamping: {left: 'clamp', right: 'clamp'},posterize: 5,},@@ -294,6 +294,8 @@ test('pasteEffects replaces existing effects with mixed static and keyframed parexpect(output).toContain("color: interpolateColors(frame, [0, 100], ['red', 'green'], {",);+ expect(output).toContain('Easing');+ expect(output).toContain('easing: [Easing.bezier(0.1, 0.2, 0.3, 0.4)]');expect(output).toContain('posterize: 5');expect(output).toContain('amount: 0.7');expect(output).not.toMatch(/color: ['"]blue['"]/);diff --git a/packages/studio-server/src/test/update-keyframes.test.ts b/packages/studio-server/src/test/update-keyframes.test.tsindex 5d6a4fe74f..5bba4768b8 100644--- a/packages/studio-server/src/test/update-keyframes.test.ts+++ b/packages/studio-server/src/test/update-keyframes.test.ts@@ -336,23 +336,27 @@ export const Example: React.FC = () => {expect(output).toContain('posterize: 2');});-test('updateSequenceKeyframes rejects easing updates for color keyframes', async () => {- await expect(- updateSequenceKeyframes({- input: colorInput,- nodePath: lineColumnToNodePath(colorInput, getLine(colorInput, '<Solid')),- updates: [- {- key: 'color',- operation: {- type: 'easing',- segmentIndex: 0,- easing: [0.42, 0, 1, 1],- },+test('updateSequenceKeyframes sets easing for color keyframes', async () => {+ const {output} = await updateSequenceKeyframes({+ input: colorInput,+ nodePath: lineColumnToNodePath(colorInput, getLine(colorInput, '<Solid')),+ updates: [+ {+ key: 'color',+ operation: {+ type: 'easing',+ segmentIndex: 0,+ easing: [0.42, 0, 1, 1],},- ],- }),- ).rejects.toThrow(/color keyframes/);+ },+ ],+ });++ expect(output).toContain('Easing');+ expect(output).toContain(+ "interpolateColors(frame, [0, 100], ['red', 'blue'], {",+ );+ expect(output).toContain('easing: [Easing.bezier(0.42, 0, 1, 1)]');});test('updateSequenceKeyframes only updates posterize for color keyframes', async () => {diff --git a/packages/studio/src/components/Timeline/update-selected-easing.ts b/packages/studio/src/components/Timeline/update-selected-easing.tsindex 2c1000f2cd..ac252f9efb 100644--- a/packages/studio/src/components/Timeline/update-selected-easing.ts+++ b/packages/studio/src/components/Timeline/update-selected-easing.ts@@ -12,6 +12,12 @@ import type {TimelineSelection} from './TimelineSelection';type EasingSelection = TimelineSelection & {type: 'easing'};export type TimelineEasingValue = 'linear' | [number, number, number, number];+const canEditEasingForInterpolationFunction = (+ interpolationFunction: string,+): boolean =>+ interpolationFunction === 'interpolate' ||+ interpolationFunction === 'interpolateColors';+const isEasingSelection = (selection: TimelineSelection,): selection is EasingSelection => selection.type === 'easing';@@ -58,7 +64,9 @@ const getSelectedEasingUpdate = ({)?.[field.fieldKey];if (sequencePropStatus?.status !== 'keyframed' ||- sequencePropStatus.interpolationFunction !== 'interpolate'+ !canEditEasingForInterpolationFunction(+ sequencePropStatus.interpolationFunction,+ )) {return null;}@@ -89,7 +97,9 @@ const getSelectedEasingUpdate = ({: null;if (effectPropStatus?.status !== 'keyframed' ||- effectPropStatus.interpolationFunction !== 'interpolate'+ !canEditEasingForInterpolationFunction(+ effectPropStatus.interpolationFunction,+ )) {return null;}diff --git a/packages/studio/src/components/Timeline/use-expanded-track-keyframe-rows.ts b/packages/studio/src/components/Timeline/use-expanded-track-keyframe-rows.tsindex ec18b11ba1..f64d3c2f14 100644--- a/packages/studio/src/components/Timeline/use-expanded-track-keyframe-rows.ts+++ b/packages/studio/src/components/Timeline/use-expanded-track-keyframe-rows.ts@@ -12,6 +12,12 @@ import {ExpandedTracksGetterContext} from '../ExpandedTracksProvider';import {getNodeKeyframes} from './get-node-keyframes';import type {getTimelineKeyframes} from './get-timeline-keyframes';+const canEditEasingForInterpolationFunction = (+ interpolationFunction: string,+): boolean =>+ interpolationFunction === 'interpolate' ||+ interpolationFunction === 'interpolateColors';+export type ExpandedTrackKeyframeRow = {readonly height: number;readonly keyframes: ReturnType<typeof getTimelineKeyframes>;@@ -40,7 +46,9 @@ const getNodeCanEditEasing = ({)?.[node.field.key];return (sequencePropStatus?.status === 'keyframed' &&- sequencePropStatus.interpolationFunction === 'interpolate'+ canEditEasingForInterpolationFunction(+ sequencePropStatus.interpolationFunction,+ ));}@@ -55,7 +63,9 @@ const getNodeCanEditEasing = ({: null;return (effectPropStatus?.status === 'keyframed' &&- effectPropStatus.interpolationFunction === 'interpolate'+ canEditEasingForInterpolationFunction(+ effectPropStatus.interpolationFunction,+ ));};