Skip to content

🎥 Make videos programmatically with React

remotion: Add outputType option to interpolate()

Jonny Burgerdd0c3e02979c
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 5621952a05..1b9413b324 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -21,12 +21,12 @@ import {
import {Folder, type TFolder} from './Folder.js';
import type {StaticFile} from './get-static-files.js';
import type {
- AssetFieldSchema,
ArrayFieldSchema,
ArrayItemFieldSchema,
+ AssetFieldSchema,
CaptionsFieldSchema,
- InteractivitySchemaField,
InteractivitySchema,
+ InteractivitySchemaField,
} from './interactivity-schema.js';
import {useIsPlayer} from './is-player.js';
import type {LogLevel} from './log.js';
@@ -227,8 +227,9 @@ export {
EasingFunction,
ExtrapolateType,
interpolate,
- InterpolateOutputOption,
InterpolateOptions,
+ InterpolateOutputOption,
+ InterpolateOutputType,
random,
RandomSeed,
} from './no-react';
@@ -346,18 +347,18 @@ export type _InternalTypes = {
export type {
AnyComposition,
- AssetFieldSchema,
ArrayFieldSchema,
ArrayItemFieldSchema,
+ AssetFieldSchema,
CaptionsFieldSchema,
DelayRenderScope,
+ InteractivitySchema,
+ InteractivitySchemaField,
JsxComponentIdentity,
LoopDisplay,
RuntimeValueSnapshot,
RuntimeValueStore,
SequenceControls,
SequenceRegistrationControls,
- InteractivitySchemaField,
- InteractivitySchema,
UseBufferState,
};
diff --git a/packages/core/src/interpolate.ts b/packages/core/src/interpolate.ts
index a259c6cfbf..d093a552fb 100644
--- a/packages/core/src/interpolate.ts
+++ b/packages/core/src/interpolate.ts
@@ -5,6 +5,12 @@ import {normalizeNumber} from './normalize-number.js';
export type ExtrapolateType = 'extend' | 'identity' | 'clamp' | 'wrap';
export type InterpolateOutputOption = 'linear' | 'perceptual-scale';
+export type InterpolateOutputType =
+ | 'font-weight'
+ | 'scale'
+ | 'translate'
+ | 'rotate'
+ | 'transform-origin';
/**
* @description This function allows you to map a range of values to another with a concise syntax
@@ -20,6 +26,7 @@ export type InterpolateOptions = Partial<{
extrapolateLeft: ExtrapolateType;
extrapolateRight: ExtrapolateType;
output: InterpolateOutputOption;
+ outputType: InterpolateOutputType;
posterize: number;
}>;
@@ -416,6 +423,7 @@ const parseAxisRotationValue = (
const parseStringInterpolationValue = (
output: string | number,
+ outputType: Exclude<InterpolateOutputType, 'font-weight'> | undefined,
): ParsedStringInterpolationValue => {
if (typeof output === 'number') {
if (!Number.isFinite(output)) {
@@ -433,8 +441,29 @@ const parseStringInterpolationValue = (
};
}
+ if (outputType === 'transform-origin') {
+ const transformOriginParts = output.trim().split(/\s+/);
+ if (
+ transformOriginParts.length < 1 ||
+ transformOriginParts.length > 3 ||
+ transformOriginParts[0] === ''
+ ) {
+ throw new TypeError(
+ `String outputRange values must contain 1 to 3 components, but got "${output}"`,
+ );
+ }
+
+ return parseTransformOriginValue(output, transformOriginParts);
+ }
+
const axisRotation = parseAxisRotationValue(output);
if (axisRotation !== null) {
+ if (outputType !== undefined && outputType !== 'rotate') {
+ throw new TypeError(
+ `Cannot interpolate "${output}" as ${outputType} because it is a rotate value`,
+ );
+ }
+
return axisRotation;
}
@@ -461,6 +490,12 @@ const parseStringInterpolationValue = (
}
}
+ if (outputType !== undefined && outputType !== kind) {
+ throw new TypeError(
+ `Cannot interpolate "${output}" as ${outputType} because it is a ${kind} value`,
+ );
+ }
+
if (kind === 'scale') {
const x = parsed[0].value;
const y = parsed[1]?.value ?? x;
@@ -754,8 +789,11 @@ const interpolateString = ({
outputRange: readonly (string | number)[];
options: InterpolateOptions | undefined;
}): string => {
- const initiallyParsedOutputRange = outputRange.map(
- parseStringInterpolationValue,
+ const initiallyParsedOutputRange = outputRange.map((output) =>
+ parseStringInterpolationValue(
+ output,
+ options?.outputType === 'font-weight' ? undefined : options?.outputType,
+ ),
);
const hasAxisRotation = initiallyParsedOutputRange.some(
(parsed) => parsed.axisRotation,
@@ -898,6 +936,49 @@ const interpolateString = ({
});
};
+const interpolateFontWeight = ({
+ input,
+ inputRange,
+ outputRange,
+ options,
+}: {
+ input: number;
+ inputRange: readonly number[];
+ outputRange: readonly (number | string)[];
+ options: InterpolateOptions | undefined;
+}): number => {
+ const normalizedOutputRange = outputRange.map((output) => {
+ if (output === 'normal') {
+ return 400;
+ }
+
+ if (output === 'bold') {
+ return 700;
+ }
+
+ const value =
+ typeof output === 'number'
+ ? output
+ : cssNumberRegex.exec(output)?.[2] === undefined
+ ? Number(output)
+ : Number.NaN;
+ if (!Number.isFinite(value) || value < 1 || value > 1000) {
+ throw new TypeError(
+ `Cannot interpolate font weight "${output}". Expected "normal", "bold", or a number between 1 and 1000`,
+ );
+ }
+
+ return value;
+ });
+
+ return interpolateNumber({
+ input,
+ inputRange,
+ outputRange: normalizedOutputRange,
+ options,
+ });
+};
+
const interpolateDiscreteString = ({
input,
inputRange,
@@ -1124,6 +1205,25 @@ function assertValidInterpolateOutputOption(
);
}
+function assertValidInterpolateOutputType(
+ outputType: InterpolateOptions['outputType'],
+) {
+ if (
+ outputType === undefined ||
+ outputType === 'font-weight' ||
+ outputType === 'scale' ||
+ outputType === 'translate' ||
+ outputType === 'rotate' ||
+ outputType === 'transform-origin'
+ ) {
+ return;
+ }
+
+ throw new Error(
+ `outputType must be "font-weight", "scale", "translate", "rotate", or "transform-origin", but got ${String(outputType)}`,
+ );
+}
+
/*
* @description Allows you to map a range of values to another using a concise syntax.
* @see [Documentation](https://remotion.dev/docs/interpolate)
@@ -1135,6 +1235,12 @@ export function interpolate(
outputRange: readonly number[],
options?: InterpolateOptions,
): number;
+export function interpolate(
+ input: number,
+ inputRange: readonly number[],
+ outputRange: readonly (number | string)[],
+ options: InterpolateOptions & {outputType: 'font-weight'},
+): number;
export function interpolate(
input: number,
inputRange: readonly number[],
@@ -1193,6 +1299,7 @@ export function interpolate(
assertValidInterpolateEasingOption(options?.easing, inputRange.length);
assertValidInterpolatePosterizeOption(options?.posterize);
assertValidInterpolateOutputOption(options?.output);
+ assertValidInterpolateOutputType(options?.outputType);
if (typeof input !== 'number') {
throw new TypeError('Cannot interpolate an input which is not a number');
@@ -1202,9 +1309,38 @@ export function interpolate(
throw new Error('outputRange must contain only numbers');
}
+ if (options?.outputType === 'font-weight') {
+ if (
+ !outputRange.every(
+ (output) => typeof output === 'number' || typeof output === 'string',
+ )
+ ) {
+ throw new TypeError(
+ 'Font weight outputRange must contain only numbers or strings',
+ );
+ }
+
+ return interpolateFontWeight({
+ input,
+ inputRange,
+ outputRange,
+ options,
+ });
+ }
+
const hasStringOutput = outputRange.some(
(output) => typeof output === 'string',
);
+ if (
+ options?.outputType !== undefined &&
+ options.outputType !== 'scale' &&
+ !hasStringOutput
+ ) {
+ throw new TypeError(
+ `${options.outputType} outputRange must contain strings with the appropriate CSS units`,
+ );
+ }
+
if (hasStringOutput) {
if (
!outputRange.every(
@@ -1225,7 +1361,12 @@ export function interpolate(
const hasNonNumericString = outputRange.some((output) => {
try {
- parseStringInterpolationValue(output);
+ parseStringInterpolationValue(
+ output,
+ options?.outputType === 'font-weight'
+ ? undefined
+ : options?.outputType,
+ );
return false;
} catch (parseError) {
return parseError instanceof UnsupportedStringInterpolationValueError;
diff --git a/packages/core/src/no-react.ts b/packages/core/src/no-react.ts
index a26d75870f..a0e96a18c1 100644
--- a/packages/core/src/no-react.ts
+++ b/packages/core/src/no-react.ts
@@ -13,8 +13,9 @@ export {
export type {
EasingFunction,
ExtrapolateType,
- InterpolateOutputOption,
InterpolateOptions,
+ InterpolateOutputOption,
+ InterpolateOutputType,
} from './interpolate';
export {random} from './random.js';
export type {RandomSeed} from './random.js';
diff --git a/packages/core/src/test/interpolate.test.ts b/packages/core/src/test/interpolate.test.ts
index acce6c8e64..ff0920ca27 100644
--- a/packages/core/src/test/interpolate.test.ts
+++ b/packages/core/src/test/interpolate.test.ts
@@ -87,6 +87,65 @@ test('A single non-numeric string keyframe does not require easing', () => {
expect(interpolate(100, [20], ['default'])).toBe('default');
});
+test('Can interpolate font weights with an explicit output type', () => {
+ expect(
+ interpolate(0.5, [0, 1], ['normal', 'bold'], {
+ outputType: 'font-weight',
+ }),
+ ).toBe(550);
+ expect(
+ interpolate(0.5, [0, 1], ['100', 900], {
+ outputType: 'font-weight',
+ }),
+ ).toBe(500);
+});
+
+test('Font weight keywords require an explicit output type', () => {
+ expectToThrow(
+ () => interpolate(0.5, [0, 1], ['normal', 'bold']),
+ /Non-numeric strings can only be interpolated using Easing\.step1/,
+ );
+});
+
+test('Font weights must be absolute values in the CSS range', () => {
+ expectToThrow(
+ () =>
+ interpolate(0.5, [0, 1], ['lighter', 'bold'], {
+ outputType: 'font-weight',
+ }),
+ /Expected "normal", "bold", or a number between 1 and 1000/,
+ );
+ expectToThrow(
+ () =>
+ interpolate(0.5, [0, 1], [0, 1001], {
+ outputType: 'font-weight',
+ }),
+ /Expected "normal", "bold", or a number between 1 and 1000/,
+ );
+});
+
+test('Explicit string output types validate the output range', () => {
+ expect(
+ interpolate(0.5, [0, 1], ['0deg', '90deg'], {outputType: 'rotate'}),
+ ).toBe('45deg');
+ expect(
+ interpolate(0.5, [0, 1], ['left top', 'right bottom'], {
+ outputType: 'transform-origin',
+ }),
+ ).toBe('50% 50%');
+ expectToThrow(
+ () =>
+ interpolate(0.5, [0, 1], ['0deg', '90deg'], {
+ outputType: 'translate',
+ }),
+ /as translate because it is a rotate value/,
+ );
+ expectToThrow(
+ () => interpolate(0.5, [0, 1], [0, 90], {outputType: 'rotate'}),
+ /rotate outputRange must contain strings with the appropriate CSS units/,
+ );
+});
+
test('Easing array with one keyframe accepts no entries', () => {
expect(
interpolate(0.5, [0], [1], {
diff --git a/packages/docs/docs/interpolate.mdx b/packages/docs/docs/interpolate.mdx
index d9ae4bb7b0..55d82267ef 100644
--- a/packages/docs/docs/interpolate.mdx
+++ b/packages/docs/docs/interpolate.mdx
@@ -166,6 +166,34 @@ All values in one interpolation must have the same type.
For each component, units must match.
For missing dimensions, CSS defaults are used: scale defaults to `1`, translate and rotate default to `0`, and transform origin defaults to `50% 50% 0`.
+Use `outputType` to explicitly select and validate the CSS value type:
+
+```tsx twoslash
+import {interpolate} from 'remotion';
+
+const rotation = interpolate(0.5, [0, 1], ['0deg', '90deg'], {
+ outputType: 'rotate',
+});
+```
+
+Supported values are `'scale'`, `'translate'`, `'rotate'`, `'transform-origin'`, and `'font-weight'`.
+If omitted, scale, translate, rotate, and transform origin values continue to be inferred.
+
+## Example: Font weights
+
+Font weight keywords require `outputType: 'font-weight'`.
+The keywords `normal` and `bold` are normalized to `400` and `700`.
+Numeric strings and numbers between `1` and `1000` are also supported.
+The result is a number.
+
+```tsx twoslash
+import {interpolate} from 'remotion';
+
+const fontWeight = interpolate(0.5, [0, 1], ['normal', 'bold'], {
+ outputType: 'font-weight',
+}); // 550
+```
+
## Example: Discrete string values<AvailableFrom v="4.0.509" />
Use `Easing.step1` to switch between strings that cannot be blended. The previous value is held until the next keyframe.
@@ -304,6 +332,12 @@ For `[0, -1]` at progress `0.5`, the result is `-Math.sqrt(0.5)`.
`easing` still controls time and progress.
`output` controls the value distribution after easing.
+### outputType?
+
+Explicitly selects the output value syntax.
+Accepts `'font-weight'`, `'scale'`, `'translate'`, `'rotate'`, or `'transform-origin'`.
+Font weight keywords are only supported when this option is set to `'font-weight'`.
+
### posterize<AvailableFrom v="4.0.470" />
_Default_: no posterization
@@ -327,12 +361,18 @@ With `posterize: 3`, frames `0`, `1`, and `2` use the value for frame `0`; frame
Since `v3.3.77`, types for the options are exported from Remotion.
```tsx twoslash
-import {ExtrapolateType, InterpolateOptions} from 'remotion';
+import {
+ ExtrapolateType,
+ InterpolateOptions,
+ InterpolateOutputType,
+} from 'remotion';
const extrapolate: ExtrapolateType = 'clamp';
+const outputType: InterpolateOutputType = 'rotate';
const option: InterpolateOptions = {
extrapolateLeft: extrapolate,
output: 'perceptual-scale',
+ outputType,
posterize: 3,
};
```