Skip to content

🎥 Make videos programmatically with React

`@remotion/effects`: Add halftone color modes (#7675)

Jonny Burgerdabc12939b57
diff --git a/packages/docs/components/demos/index.tsx b/packages/docs/components/demos/index.tsx
index ed3ac378d7..0b6d4f493e 100644
--- a/packages/docs/components/demos/index.tsx
+++ b/packages/docs/components/demos/index.tsx
@@ -4,7 +4,7 @@ import React, {useCallback, useMemo, useState} from 'react';
import {AbsoluteFill} from 'remotion';
import {Control} from './control';
import styles from './styles.module.css';
-import type {DemoType} from './types';
+import type {DemoType, Option} from './types';
import {
animationMathDemo,
arrowDemo,
@@ -149,6 +149,17 @@ const demos: DemoType[] = [
swapPresentationDemo,
];
+const shouldShowOption = (
+ option: Option,
+ state: Record<string, unknown>,
+): boolean => {
+ if (!option.showIf) {
+ return true;
+ }
+
+ return state[option.showIf.option] === option.showIf.value;
+};
+
export const Demo: React.FC<{
readonly type: string;
}> = ({type}) => {
@@ -238,21 +249,23 @@ export const Demo: React.FC<{
loop
/>
<div className={styles.containerrow}>
- {demo.options.map((option) => {
- return (
- <Control
- key={option.name}
- option={option}
- value={state[option.name]}
- setValue={(value) => {
- setState((s) => ({
- ...s,
- [option.name]: value,
- }));
- }}
- />
- );
- })}
+ {demo.options
+ .filter((option) => shouldShowOption(option, state))
+ .map((option) => {
+ return (
+ <Control
+ key={option.name}
+ option={option}
+ value={state[option.name]}
+ setValue={(value) => {
+ setState((s) => ({
+ ...s,
+ [option.name]: value,
+ }));
+ }}
+ />
+ );
+ })}
</div>
</div>
);
diff --git a/packages/docs/components/demos/types.ts b/packages/docs/components/demos/types.ts
index 81325ed4bb..014bd61be4 100644
--- a/packages/docs/components/demos/types.ts
+++ b/packages/docs/components/demos/types.ts
@@ -73,6 +73,10 @@ import {ZoomInOutDocsDemo} from './ZoomInOutDemo';
export type Option = {
name: string;
optional: 'no' | 'default-enabled' | 'default-disabled';
+ showIf?: {
+ option: string;
+ value: string | number | boolean | null;
+ };
} & (
| {
type: 'numeric';
@@ -1879,10 +1883,21 @@ export const effectsHalftoneDemo: DemoType = {
optional: 'no',
},
{
- name: 'color',
+ name: 'colorMode',
+ type: 'enum',
+ values: ['solid', 'source'],
+ default: 'solid',
+ optional: 'no',
+ },
+ {
+ name: 'dotColor',
type: 'color',
- default: '#0b84f3',
+ default: '#ff0000',
optional: 'no',
+ showIf: {
+ option: 'colorMode',
+ value: 'solid',
+ },
},
{
name: 'invert',
diff --git a/packages/docs/components/effects/effects-halftone-preview.tsx b/packages/docs/components/effects/effects-halftone-preview.tsx
index ea1e402152..f96498f384 100644
--- a/packages/docs/components/effects/effects-halftone-preview.tsx
+++ b/packages/docs/components/effects/effects-halftone-preview.tsx
@@ -1,4 +1,7 @@
-import type {HalftoneShape} from '@remotion/effects/halftone';
+import type {
+ HalftoneColorMode,
+ HalftoneShape,
+} from '@remotion/effects/halftone';
import {halftone} from '@remotion/effects/halftone';
import React from 'react';
import {CanvasImage} from 'remotion';
@@ -9,9 +12,15 @@ export const EffectsHalftonePreview: React.FC<{
readonly dotSize: number;
readonly dotSpacing: number;
readonly rotation: number;
- readonly color: string;
+ readonly colorMode: HalftoneColorMode;
+ readonly dotColor: string;
readonly invert: boolean;
-}> = ({shape, dotSize, dotSpacing, rotation, color, invert}) => {
+}> = ({shape, dotSize, dotSpacing, rotation, colorMode, dotColor, invert}) => {
+ const colorParams =
+ colorMode === 'source'
+ ? ({colorMode: 'source'} as const)
+ : ({colorMode: 'solid', dotColor} as const);
+
return (
<CanvasImage
src={EFFECTS_PREVIEW_IMAGE_SRC}
@@ -23,7 +32,7 @@ export const EffectsHalftonePreview: React.FC<{
dotSize,
dotSpacing,
rotation,
- color,
+ ...colorParams,
invert,
}),
]}
diff --git a/packages/docs/docs/effects/halftone.mdx b/packages/docs/docs/effects/halftone.mdx
index 655aa7fd5a..6b0894ebc2 100644
--- a/packages/docs/docs/effects/halftone.mdx
+++ b/packages/docs/docs/effects/halftone.mdx
@@ -6,7 +6,7 @@ sidebar_label: halftone()
crumb: '@remotion/effects'
---
-# halftone()<AvailableFrom v="4.0.466" />
+# halftone()<AvailableFrom v="4.0.467" />
_Part of the [`@remotion/effects`](/docs/effects/api) package._
@@ -36,7 +36,34 @@ export const MyComp: React.FC = () => {
dotSize: 18,
dotSpacing: 20,
rotation: 12,
- color: '#111827',
+ dotColor: 'red',
+ }),
+ ]}
+ />
+ </AbsoluteFill>
+ );
+};
+```
+
+To preserve the original color of each sampled grid cell, set `colorMode` to `'source'`:
+
+```tsx twoslash title="MyComp.tsx"
+import {AbsoluteFill} from 'remotion';
+import {Video} from '@remotion/media';
+import {halftone} from '@remotion/effects/halftone';
+
+export const MyComp: React.FC = () => {
+ return (
+ <AbsoluteFill>
+ <Video
+ src="https://remotion.media/video.mp4"
+ effects={[
+ halftone({
+ shape: 'circle',
+ dotSize: 18,
+ dotSpacing: 20,
+ rotation: 12,
+ colorMode: 'source',
}),
]}
/>
@@ -83,9 +110,19 @@ Texture sampling mode used when reading luminance from the source. Defaults to `
Allowed values are `'bilinear'` and `'nearest'`.
-### `color?`
+### `colorMode?`
+
+Controls how dots are colored. Defaults to `'solid'`.
+
+Allowed values are `'solid'` and `'source'`.
+
+When set to `'solid'`, each dot uses `dotColor`. When set to `'source'`, each dot uses the sampled source color at the grid cell.
+
+If `colorMode` is `'source'`, don't pass `dotColor`.
+
+### `dotColor?`
-Color of the dots. Defaults to `'black'`.
+Color of the dots when `colorMode` is `'solid'`. Defaults to `'red'`.
### `invert?`
diff --git a/packages/effects/src/halftone.ts b/packages/effects/src/halftone.ts
index 828b939f7e..fc7ff68b39 100644
--- a/packages/effects/src/halftone.ts
+++ b/packages/effects/src/halftone.ts
@@ -6,6 +6,7 @@ import {assertEffectParamsObject} from './validate-effect-param.js';
const {createEffect, createWebGL2ContextError} = Internals;
const HALFTONE_SHAPES = ['circle', 'square', 'line'] as const;
const HALFTONE_SAMPLING = ['bilinear', 'nearest'] as const;
+const HALFTONE_COLOR_MODES = ['solid', 'source'] as const;
export const halftoneSchema = {
dotSize: {
@@ -59,17 +60,28 @@ export const halftoneSchema = {
default: false,
description: 'Invert',
},
- color: {
- type: 'color',
- default: 'black',
- description: 'Color',
+ colorMode: {
+ type: 'enum',
+ default: 'solid' as const,
+ description: 'Color mode',
+ variants: {
+ solid: {
+ dotColor: {
+ type: 'color',
+ default: 'red',
+ description: 'Dot color',
+ },
+ },
+ source: {},
+ },
},
} as const satisfies SequenceSchema;
export type HalftoneShape = (typeof HALFTONE_SHAPES)[number];
export type HalftoneSampling = (typeof HALFTONE_SAMPLING)[number];
+export type HalftoneColorMode = (typeof HALFTONE_COLOR_MODES)[number];
-export type HalftoneParams = {
+type HalftoneCommonParams = {
readonly shape?: HalftoneShape;
readonly dotSize?: number;
/**
@@ -81,8 +93,6 @@ export type HalftoneParams = {
readonly offsetX?: number;
readonly offsetY?: number;
readonly sampling?: HalftoneSampling;
- /** Dot color. Defaults to black. */
- readonly color?: string;
/**
* When false (default), dark areas produce larger dots.
* When true, the pattern is inverted:
@@ -91,6 +101,18 @@ export type HalftoneParams = {
readonly invert?: boolean;
};
+export type HalftoneParams = HalftoneCommonParams &
+ (
+ | {
+ readonly colorMode?: 'solid';
+ /** Dot color. Defaults to red. */
+ readonly dotColor?: string;
+ }
+ | {
+ readonly colorMode: 'source';
+ }
+ );
+
type HalftoneResolved = {
shape: HalftoneShape;
dotSize: number;
@@ -99,7 +121,8 @@ type HalftoneResolved = {
offsetX: number;
offsetY: number;
sampling: HalftoneSampling;
- color: string;
+ colorMode: HalftoneColorMode;
+ dotColor: string;
invert: boolean;
};
@@ -160,7 +183,8 @@ const resolve = (p: HalftoneParams): HalftoneResolved => ({
offsetX: p.offsetX ?? 0,
offsetY: p.offsetY ?? 0,
sampling: p.sampling ?? 'bilinear',
- color: p.color ?? 'black',
+ colorMode: p.colorMode ?? 'solid',
+ dotColor: 'dotColor' in p ? (p.dotColor ?? 'red') : 'red',
invert: p.invert ?? false,
});
@@ -173,7 +197,21 @@ const validateHalftoneParams = (params: HalftoneParams): void => {
assertOptionalFiniteNumber(params.offsetY, 'offsetY');
assertOptionalEnum(params.shape, 'shape', HALFTONE_SHAPES);
assertOptionalEnum(params.sampling, 'sampling', HALFTONE_SAMPLING);
- assertOptionalColor(params.color, 'color');
+ assertOptionalEnum(params.colorMode, 'colorMode', HALFTONE_COLOR_MODES);
+ if ('color' in params && params.color !== undefined) {
+ throw new TypeError('"color" has been renamed to "dotColor"');
+ }
+
+ if (params.colorMode === 'source' && 'dotColor' in params) {
+ throw new TypeError(
+ '"dotColor" can only be set when "colorMode" is "solid"',
+ );
+ }
+
+ assertOptionalColor(
+ 'dotColor' in params ? params.dotColor : undefined,
+ 'dotColor',
+ );
assertOptionalBoolean(params.invert, 'invert');
if (params.dotSize !== undefined && params.dotSize < 1) {
@@ -214,6 +252,7 @@ uniform vec2 uOffset;
uniform vec4 uColor;
uniform int uShape;
uniform bool uShadeOutside;
+uniform bool uUseSourceColor;
void main() {
vec2 fragPos = vUv * uResolution;
@@ -272,7 +311,7 @@ void main() {
* (1.0 - smoothstep(lineHalf - 0.5, lineHalf + 0.5, abs(diff.y)));
}
- fragColor = uColor * coverage;
+ fragColor = (uUseSourceColor ? texColor : uColor) * coverage;
}
`;
@@ -291,6 +330,7 @@ type HalftoneState = {
uColor: WebGLUniformLocation | null;
uShape: WebGLUniformLocation | null;
uShadeOutside: WebGLUniformLocation | null;
+ uUseSourceColor: WebGLUniformLocation | null;
colorCtx: CanvasRenderingContext2D;
cachedColorStr: string;
cachedColorRgba: [number, number, number, number];
@@ -362,6 +402,8 @@ const parseColorRgba = (
// (defaults to `dotSize`). `sampling` controls texture interpolation when
// reading luminance at grid centres. `invert` inverts the pattern so
// bright/transparent areas produce larger dots and dark areas produce fewer.
+// `colorMode` controls whether dots use a solid `dotColor` or the sampled source
+// color at each grid cell.
export const halftone = createEffect<HalftoneParams, HalftoneState>({
type: 'remotion/halftone',
label: 'Halftone',
@@ -369,7 +411,7 @@ export const halftone = createEffect<HalftoneParams, HalftoneState>({
backend: 'webgl2',
calculateKey: (params) => {
const r = resolve(params);
- return `halftone-${r.shape}-${r.dotSize}-${r.dotSpacing}-${r.rotation}-${r.offsetX}-${r.offsetY}-${r.sampling}-${r.color}-${r.invert ? 1 : 0}`;
+ return `halftone-${r.shape}-${r.dotSize}-${r.dotSpacing}-${r.rotation}-${r.offsetX}-${r.offsetY}-${r.sampling}-${r.colorMode}-${r.dotColor}-${r.invert ? 1 : 0}`;
},
setup: (target) => {
const gl = target.getContext('webgl2', {
@@ -450,6 +492,7 @@ export const halftone = createEffect<HalftoneParams, HalftoneState>({
uColor: gl.getUniformLocation(program, 'uColor'),
uShape: gl.getUniformLocation(program, 'uShape'),
uShadeOutside: gl.getUniformLocation(program, 'uShadeOutside'),
+ uUseSourceColor: gl.getUniformLocation(program, 'uUseSourceColor'),
colorCtx,
cachedColorStr: '',
cachedColorRgba: [0, 0, 0, 1] as [number, number, number, number],
@@ -459,9 +502,9 @@ export const halftone = createEffect<HalftoneParams, HalftoneState>({
const r = resolve(params);
const {gl, program, vao, texture} = state;
- if (state.cachedColorStr !== r.color) {
- state.cachedColorStr = r.color;
- state.cachedColorRgba = parseColorRgba(state.colorCtx, r.color);
+ if (state.cachedColorStr !== r.dotColor) {
+ state.cachedColorStr = r.dotColor;
+ state.cachedColorRgba = parseColorRgba(state.colorCtx, r.dotColor);
}
const [cr, cg, cb, ca] = state.cachedColorRgba;
@@ -500,6 +543,8 @@ export const halftone = createEffect<HalftoneParams, HalftoneState>({
if (state.uShape) gl.uniform1i(state.uShape, SHAPE_INDEX[r.shape]);
if (state.uShadeOutside)
gl.uniform1i(state.uShadeOutside, r.invert ? 1 : 0);
+ if (state.uUseSourceColor)
+ gl.uniform1i(state.uUseSourceColor, r.colorMode === 'source' ? 1 : 0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.ts
index e3512b1a45..01c2f7da51 100644
--- a/packages/effects/src/test/effect-params.test.ts
+++ b/packages/effects/src/test/effect-params.test.ts
@@ -293,12 +293,48 @@ test('halftone() rejects dotSize below range', () => {
expect(() => halftone({dotSize: 0})).toThrow('"dotSize" must be >= 1');
});
-test('halftone() rejects empty color strings', () => {
- expect(() => halftone({color: ''})).toThrow(
- '"color" must be a non-empty string, but got ""',
+test('halftone() rejects empty dotColor strings', () => {
+ expect(() => halftone({dotColor: ''})).toThrow(
+ '"dotColor" must be a non-empty string, but got ""',
);
});
+test('halftone() rejects color outside the enum', () => {
+ expect(() =>
+ halftone({
+ colorMode: 'cmyk' as Exclude<
+ Parameters<typeof halftone>[0],
+ undefined
+ >['colorMode'],
+ }),
+ ).toThrow('"colorMode" must be "solid" or "source"');
+});
+
+test('halftone() rejects the renamed color option', () => {
+ expect(() =>
+ halftone({
+ color: 'black',
+ } as Parameters<typeof halftone>[0]),
+ ).toThrow('"color" has been renamed to "dotColor"');
+});
+
+test('halftone() ignores undefined legacy color option', () => {
+ expect(() =>
+ halftone({
+ color: undefined,
+ } as Parameters<typeof halftone>[0]),
+ ).not.toThrow();
+});
+
+test('halftone() rejects dotColor for source color mode', () => {
+ expect(() =>
+ halftone({
+ colorMode: 'source',
+ dotColor: 'black',
+ } as Parameters<typeof halftone>[0]),
+ ).toThrow('"dotColor" can only be set when "colorMode" is "solid"');
+});
+
test('invert() accepts default params', () => {
expect(() => invert()).not.toThrow();
});
diff --git a/packages/example/src/EffectsTestbed/EffectsTestbed.tsx b/packages/example/src/EffectsTestbed/EffectsTestbed.tsx
index 47c1422565..d0a2a72cb9 100644
--- a/packages/example/src/EffectsTestbed/EffectsTestbed.tsx
+++ b/packages/example/src/EffectsTestbed/EffectsTestbed.tsx
@@ -192,7 +192,24 @@ export const EffectsTestbed: React.FC = () => {
shape: 'circle',
dotSize: 12,
dotSpacing: 12,
- color: '#000',
+ dotColor: '#000',
+ }),
+ ]}
+ />
+ </Tile>
+ <Tile title="halftone source" subtitle="preserves sampled colors">
+ <Video
+ src={SAMPLE_VIDEO}
+ style={tileVideoStyle}
+ muted
+ loop
+ objectFit="cover"
+ effects={[
+ halftone({
+ shape: 'circle',
+ dotSize: 12,
+ dotSpacing: 12,
+ colorMode: 'source',
}),
]}
/>
diff --git a/packages/example/src/Gif/GifEffects.tsx b/packages/example/src/Gif/GifEffects.tsx
index cefece5ae6..888bffb1b6 100644
--- a/packages/example/src/Gif/GifEffects.tsx
+++ b/packages/example/src/Gif/GifEffects.tsx
@@ -183,7 +183,7 @@ const Comp: React.FC = () => {
shape: 'circle',
dotSize: 12,
dotSpacing: 12,
- color: '#000',
+ dotColor: '#000',
}),
]}
/>
diff --git a/packages/example/src/HtmlInCanvas/effects-halftone-preview.tsx b/packages/example/src/HtmlInCanvas/effects-halftone-preview.tsx
index 3820bf2b9e..1b12ba307f 100644
--- a/packages/example/src/HtmlInCanvas/effects-halftone-preview.tsx
+++ b/packages/example/src/HtmlInCanvas/effects-halftone-preview.tsx
@@ -16,7 +16,7 @@ export const EffectsHalftonePreview: React.FC = () => {
dotSize: 8,
dotSpacing: 7,
rotation: 12,
- color: '#0b84f3',
+ dotColor: '#0b84f3',
}),
]}
>
diff --git a/packages/example/src/Rive/RiveEffects.tsx b/packages/example/src/Rive/RiveEffects.tsx
index 35a438d989..09e4e20eaf 100644
--- a/packages/example/src/Rive/RiveEffects.tsx
+++ b/packages/example/src/Rive/RiveEffects.tsx
@@ -175,7 +175,7 @@ const Comp: React.FC = () => {
shape: 'circle',
dotSize: 12,
dotSpacing: 12,
- color: '#000',
+ dotColor: '#000',
}),
]}
/>
diff --git a/packages/studio-server/src/codemods/update-effect-props/update-effect-props.ts b/packages/studio-server/src/codemods/update-effect-props/update-effect-props.ts
index 402fbfa162..f4a2fba912 100644
--- a/packages/studio-server/src/codemods/update-effect-props/update-effect-props.ts
+++ b/packages/studio-server/src/codemods/update-effect-props/update-effect-props.ts
@@ -10,7 +10,8 @@ import type {
import {stringifyDefaultProps} from '@remotion/studio-shared';
import type {ExpressionKind} from 'ast-types/lib/gen/kinds';
import * as recast from 'recast';
-import type {SequenceNodePath} from 'remotion';
+import type {SequenceNodePath, SequenceSchema} from 'remotion';
+import {NoReactInternals} from 'remotion/no-react';
import {findJsxElementAtNodePath} from '../../preview-server/routes/can-update-sequence-props';
import {formatFileContent} from '../format-file-content';
import {parseAst, serializeAst} from '../parse-ast';
@@ -29,6 +30,12 @@ export type UpdateEffectPropsResult = {
oldValueString: string;
logLine: number;
effectCallee: string;
+ removedProps: PropDelta[];
+};
+
+export type PropDelta = {
+ key: string;
+ valueString: string;
};
const parseValueExpression = (value: unknown): ExpressionKind => {
@@ -172,21 +179,52 @@ const findObjectProperty = (
};
};
+const printObjectPropertyValue = (prop: ObjectProperty) =>
+ recast
+ .print(prop.value)
+ .code.replace(/[\n\r\t]+/g, ' ')
+ .replace(/,(\s*[}\]])/g, '$1')
+ .trim();
+
+const removeObjectProperty = ({
+ objExpr,
+ propertyName,
+}: {
+ objExpr: ObjectExpression;
+ propertyName: string;
+}): PropDelta | null => {
+ const {propIndex, prop} = findObjectProperty(objExpr, propertyName);
+ if (!prop || propIndex === -1) {
+ return null;
+ }
+
+ const valueString = printObjectPropertyValue(prop);
+ objExpr.properties.splice(propIndex, 1);
+
+ return {
+ key: propertyName,
+ valueString,
+ };
+};
+
export const updateEffectPropsAst = ({
input,
sequenceNodePath,
effectIndex,
update,
+ schema,
}: {
input: string;
sequenceNodePath: SequenceNodePath;
effectIndex: number;
update: EffectPropUpdate;
+ schema: SequenceSchema;
}): {
serialized: string;
oldValueString: string;
logLine: number;
effectCallee: string;
+ removedProps: PropDelta[];
} => {
const ast = parseAst(input);
const jsx = findJsxElementAtNodePath(ast, sequenceNodePath);
@@ -225,6 +263,7 @@ export const updateEffectPropsAst = ({
oldValueString: '',
logLine: call.loc?.start.line ?? jsx.loc?.start.line ?? 1,
effectCallee,
+ removedProps: [],
};
}
@@ -237,6 +276,7 @@ export const updateEffectPropsAst = ({
}
const {prop} = findObjectProperty(objExpr, update.key);
+ const removedProps: PropDelta[] = [];
let oldValueString = '';
if (prop) {
@@ -266,6 +306,24 @@ export const updateEffectPropsAst = ({
}
}
+ const fieldSchema = schema[update.key];
+ if (fieldSchema && fieldSchema.type === 'enum') {
+ const propsToDelete = NoReactInternals.findPropsToDelete({
+ schema,
+ key: update.key,
+ value: update.value,
+ });
+ for (const propToDelete of propsToDelete) {
+ const removed = removeObjectProperty({
+ objExpr,
+ propertyName: propToDelete,
+ });
+ if (removed) {
+ removedProps.push(removed);
+ }
+ }
+ }
+
const logLine = call.loc?.start.line ?? jsx.loc?.start.line ?? 1;
return {
@@ -273,6 +331,7 @@ export const updateEffectPropsAst = ({
oldValueString,
logLine,
effectCallee,
+ removedProps,
};
};
@@ -281,20 +340,23 @@ export const updateEffectProps = async ({
sequenceNodePath,
effectIndex,
update,
+ schema,
prettierConfigOverride,
}: {
input: string;
sequenceNodePath: SequenceNodePath;
effectIndex: number;
update: EffectPropUpdate;
+ schema: SequenceSchema;
prettierConfigOverride?: Record<string, unknown> | null;
}): Promise<UpdateEffectPropsResult> => {
- const {serialized, oldValueString, logLine, effectCallee} =
+ const {serialized, oldValueString, logLine, effectCallee, removedProps} =
updateEffectPropsAst({
input,
sequenceNodePath,
effectIndex,
update,
+ schema,
});
const {output, formatted} = await formatFileContent({
@@ -308,5 +370,6 @@ export const updateEffectProps = async ({
formatted,
logLine,
effectCallee,
+ removedProps,
};
};
diff --git a/packages/studio-server/src/preview-server/routes/save-effect-props.ts b/packages/studio-server/src/preview-server/routes/save-effect-props.ts
index 1ebc1992d2..b93ef7843d 100644
--- a/packages/studio-server/src/preview-server/routes/save-effect-props.ts
+++ b/packages/studio-server/src/preview-server/routes/save-effect-props.ts
@@ -56,17 +56,24 @@ export const saveEffectPropsHandler: ApiHandler<
const parsedDefault =
defaultValue !== null ? JSON.parse(defaultValue) : null;
- const {output, oldValueString, formatted, logLine, effectCallee} =
- await updateEffectProps({
- input: fileContents,
- sequenceNodePath: sequenceNodePath.nodePath,
- effectIndex,
- update: {
- key,
- value: JSON.parse(value),
- defaultValue: parsedDefault,
- },
- });
+ const {
+ output,
+ oldValueString,
+ formatted,
+ logLine,
+ effectCallee,
+ removedProps,
+ } = await updateEffectProps({
+ input: fileContents,
+ sequenceNodePath: sequenceNodePath.nodePath,
+ effectIndex,
+ update: {
+ key,
+ value: JSON.parse(value),
+ defaultValue: parsedDefault,
+ },
+ schema,
+ });
const defaultValueString =
parsedDefault !== null ? JSON.stringify(parsedDefault) : null;
@@ -75,6 +82,10 @@ export const saveEffectPropsHandler: ApiHandler<
const normalizedNew = normalizeQuotes(value);
const normalizedDefault =
defaultValueString !== null ? normalizeQuotes(defaultValueString) : null;
+ const normalizedRemovedProps = removedProps.map((prop) => ({
+ ...prop,
+ valueString: normalizeQuotes(prop.valueString),
+ }));
const undoPropChange = formatEffectPropChange({
effectName: effectCallee,
@@ -83,7 +94,7 @@ export const saveEffectPropsHandler: ApiHandler<
newValueString: normalizedOld,
defaultValueString: normalizedDefault,
removedProps: [],
- addedProps: [],
+ addedProps: normalizedRemovedProps,
});
const redoPropChange = formatEffectPropChange({
effectName: effectCallee,
@@ -91,7 +102,7 @@ export const saveEffectPropsHandler: ApiHandler<
oldValueString: normalizedOld,
newValueString: normalizedNew,
defaultValueString: normalizedDefault,
- removedProps: [],
+ removedProps: normalizedRemovedProps,
addedProps: [],
});
@@ -122,7 +133,7 @@ export const saveEffectPropsHandler: ApiHandler<
defaultValueString,
formatted,
logLevel,
- removedProps: [],
+ removedProps,
addedProps: [],
});
diff --git a/packages/studio-server/src/test/update-effect-props.test.ts b/packages/studio-server/src/test/update-effect-props.test.ts
index 3a416a8f01..54123765e4 100644
--- a/packages/studio-server/src/test/update-effect-props.test.ts
+++ b/packages/studio-server/src/test/update-effect-props.test.ts
@@ -2,6 +2,21 @@ import {expect, test} from 'bun:test';
import {updateEffectPropsAst} from '../codemods/update-effect-props/update-effect-props';
import {lineColumnToNodePath} from './test-utils';
+const tintSchema = {
+ color: {
+ type: 'color',
+ default: 'black',
+ },
+ opacity: {
+ type: 'number',
+ default: 1,
+ },
+ amount: {
+ type: 'number',
+ default: 1,
+ },
+} as const;
+
const buildInput = (
effects: string,
) => `import {HtmlInCanvas} from '@remotion/html-in-canvas';
@@ -23,6 +38,7 @@ test('updateEffectProps updates an existing prop on the right effect', () => {
sequenceNodePath: lineColumnToNodePath(input, 6),
effectIndex: 0,
update: {key: 'opacity', value: 0.8, defaultValue: null},
+ schema: tintSchema,
});
expect(serialized).toContain('opacity: 0.8');
@@ -36,6 +52,7 @@ test('updateEffectProps adds a missing prop', () => {
sequenceNodePath: lineColumnToNodePath(input, 6),
effectIndex: 0,
update: {key: 'opacity', value: 0.25, defaultValue: null},
+ schema: tintSchema,
});
expect(effectCallee).toBe('tint');
@@ -50,6 +67,7 @@ test('updateEffectProps removes a prop equal to default', () => {
sequenceNodePath: lineColumnToNodePath(input, 6),
effectIndex: 0,
update: {key: 'opacity', value: 1, defaultValue: 1},
+ schema: tintSchema,
});
expect(serialized).not.toContain('opacity:');
@@ -65,6 +83,7 @@ test('updateEffectProps targets the correct effect by index when there are multi
sequenceNodePath: lineColumnToNodePath(input, 6),
effectIndex: 1,
update: {key: 'opacity', value: 0.9, defaultValue: null},
+ schema: tintSchema,
});
expect(serialized).toContain('opacity: 0.9');
@@ -80,6 +99,7 @@ test('updateEffectProps throws when effect index is out of range', () => {
sequenceNodePath: lineColumnToNodePath(input, 6),
effectIndex: 5,
update: {key: 'opacity', value: 0.5, defaultValue: null},
+ schema: tintSchema,
});
}).toThrow(/not-found/);
});
@@ -91,6 +111,7 @@ test('updateEffectProps inserts object literal when effect has no arguments', ()
sequenceNodePath: lineColumnToNodePath(input, 6),
effectIndex: 0,
update: {key: 'amount', value: 0.5, defaultValue: null},
+ schema: tintSchema,
});
expect(serialized).toContain('amount: 0.5');
@@ -105,6 +126,43 @@ test('updateEffectProps throws when first arg is not an object literal', () => {
sequenceNodePath: lineColumnToNodePath(input, 6),
effectIndex: 0,
update: {key: 'opacity', value: 0.5, defaultValue: null},
+ schema: tintSchema,
});
}).toThrow(/computed/);
});
+
+test('updateEffectProps removes props from inactive enum variants', () => {
+ const input = buildInput(
+ '[tint({colorMode: "solid", dotColor: "red blue", opacity: 0.5})]',
+ );
+ const {serialized, removedProps} = updateEffectPropsAst({
+ input,
+ sequenceNodePath: lineColumnToNodePath(input, 6),
+ effectIndex: 0,
+ update: {key: 'colorMode', value: 'source', defaultValue: 'solid'},
+ schema: {
+ colorMode: {
+ type: 'enum',
+ default: 'solid',
+ variants: {
+ solid: {
+ dotColor: {
+ type: 'color',
+ default: 'red',
+ },
+ },
+ source: {},
+ },
+ },
+ opacity: {
+ type: 'number',
+ default: 1,
+ },
+ },
+ });
+
+ expect(serialized).toContain('colorMode: "source"');
+ expect(serialized).not.toContain('dotColor');
+ expect(serialized).toContain('opacity: 0.5');
+ expect(removedProps).toEqual([{key: 'dotColor', valueString: '"red blue"'}]);
+});
diff --git a/packages/studio-shared/src/schema-field-info.ts b/packages/studio-shared/src/schema-field-info.ts
index 591ab437e9..1b901fe32b 100644
--- a/packages/studio-shared/src/schema-field-info.ts
+++ b/packages/studio-shared/src/schema-field-info.ts
@@ -1,12 +1,13 @@
import type {
CodeValues,
DragOverrides,
- SequenceControls,
- VisibleFieldSchema,
- SequenceSchema,
+ EffectDefinition,
GetDragOverrides,
+ GetEffectDragOverrides,
+ SequenceControls,
SequencePropsSubscriptionKey,
- EffectDefinition,
+ SequenceSchema,
+ VisibleFieldSchema,
} from 'remotion';
import {Internals} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
@@ -104,11 +105,48 @@ export const getFieldsToShow = ({
.filter(NoReactInternals.truthy);
};
-export const getEffectFieldsToShow = (
- effect: EffectDefinition<unknown>,
- effectIndex: number,
-): EffectSchemaFieldInfo[] => {
- return Object.entries(effect.schema)
+export const getEffectFieldsToShow = ({
+ effect,
+ effectIndex,
+ nodePath,
+ codeValues,
+ getEffectDragOverrides,
+}: {
+ effect: EffectDefinition<unknown>;
+ effectIndex: number;
+ nodePath: SequencePropsSubscriptionKey | null;
+ codeValues: CodeValues;
+ getEffectDragOverrides: GetEffectDragOverrides;
+}): EffectSchemaFieldInfo[] => {
+ const effectStatus =
+ nodePath === null
+ ? null
+ : Internals.getEffectCodeValuesCtx({
+ codeValues,
+ nodePath,
+ effectIndex,
+ });
+ const dragOverrides =
+ nodePath === null ? {} : getEffectDragOverrides(nodePath, effectIndex);
+ const activeSchema = Internals.flattenActiveSchema(effect.schema, (key) => {
+ const dragOverride = dragOverrides[key];
+ if (dragOverride !== undefined) {
+ return dragOverride;
+ }
+
+ if (effectStatus?.type !== 'can-update-effect') {
+ return undefined;
+ }
+
+ const propStatus = effectStatus.props[key];
+ if (!propStatus || !propStatus.canUpdate) {
+ return undefined;
+ }
+
+ return propStatus.codeValue;
+ });
+
+ return Object.entries(activeSchema)
.map(([key, fieldSchema]): EffectSchemaFieldInfo | null => {
const typeName = fieldSchema.type;
if (typeName === 'hidden') {
diff --git a/packages/studio-shared/src/test/schema-field-info.test.ts b/packages/studio-shared/src/test/schema-field-info.test.ts
new file mode 100644
index 0000000000..3882a81c68
--- /dev/null
+++ b/packages/studio-shared/src/test/schema-field-info.test.ts
@@ -0,0 +1,80 @@
+import {expect, test} from 'bun:test';
+import {
+ Internals,
+ type EffectDefinition,
+ type SequencePropsSubscriptionKey,
+} from 'remotion';
+import {getEffectFieldsToShow} from '../schema-field-info';
+
+const effect = {
+ type: 'test/effect',
+ label: 'Test effect',
+ documentationLink: null,
+ backend: '2d',
+ calculateKey: () => 'test',
+ setup: () => null,
+ apply: () => undefined,
+ cleanup: () => undefined,
+ validateParams: () => undefined,
+ schema: {
+ colorMode: {
+ type: 'enum',
+ default: 'solid' as const,
+ variants: {
+ solid: {
+ dotColor: {
+ type: 'color',
+ default: 'red',
+ },
+ },
+ source: {},
+ },
+ },
+ },
+} satisfies EffectDefinition<unknown>;
+
+const nodePath: SequencePropsSubscriptionKey = {
+ absolutePath: 'Comp',
+ nodePath: [],
+ sequenceKeys: [],
+ effectKeys: [],
+};
+
+test('getEffectFieldsToShow uses the active enum variant', () => {
+ const fields = getEffectFieldsToShow({
+ effect,
+ effectIndex: 0,
+ nodePath,
+ codeValues: {
+ [Internals.makeSequencePropsSubscriptionKey(nodePath)]: {
+ canUpdate: true,
+ props: {},
+ effects: [
+ {
+ canUpdate: true,
+ callee: 'halftone',
+ effectIndex: 0,
+ props: {
+ colorMode: {canUpdate: true, codeValue: 'source'},
+ },
+ },
+ ],
+ },
+ },
+ getEffectDragOverrides: () => ({}),
+ });
+
+ expect(fields.map((field) => field.key)).toEqual(['colorMode']);
+});
+
+test('getEffectFieldsToShow uses default enum variant if no code value exists', () => {
+ const fields = getEffectFieldsToShow({
+ effect,
+ effectIndex: 0,
+ nodePath: null,
+ codeValues: {},
+ getEffectDragOverrides: () => ({}),
+ });
+
+ expect(fields.map((field) => field.key)).toEqual(['colorMode', 'dotColor']);
+});
diff --git a/packages/studio/src/components/Timeline/TimelineExpandedSection.tsx b/packages/studio/src/components/Timeline/TimelineExpandedSection.tsx
index 2a0d2c0b55..e2bc6260f2 100644
--- a/packages/studio/src/components/Timeline/TimelineExpandedSection.tsx
+++ b/packages/studio/src/components/Timeline/TimelineExpandedSection.tsx
@@ -39,7 +39,7 @@ export const TimelineExpandedSection: React.FC<{
const {codeValues: visualModeCodeValues} = useContext(
Internals.VisualModeCodeValuesContext,
);
- const {getDragOverrides} = useContext(
+ const {getDragOverrides, getEffectDragOverrides} = useContext(
Internals.VisualModeDragOverridesContext,
);
@@ -49,9 +49,16 @@ export const TimelineExpandedSection: React.FC<{
sequence,
nodePathInfo,
getDragOverrides,
+ getEffectDragOverrides,
codeValues: visualModeCodeValues,
}),
- [sequence, nodePathInfo, getDragOverrides, visualModeCodeValues],
+ [
+ sequence,
+ nodePathInfo,
+ getDragOverrides,
+ getEffectDragOverrides,
+ visualModeCodeValues,
+ ],
);
const flat = useMemo(
diff --git a/packages/studio/src/components/Timeline/TimelineExpandedTrackKeyframes.tsx b/packages/studio/src/components/Timeline/TimelineExpandedTrackKeyframes.tsx
index db60c6cbbb..98a7c55740 100644
--- a/packages/studio/src/components/Timeline/TimelineExpandedTrackKeyframes.tsx
+++ b/packages/studio/src/components/Timeline/TimelineExpandedTrackKeyframes.tsx
@@ -87,6 +87,7 @@ const TimelineExpandedTrackKeyframesInner: React.FC<{
sequence,
nodePathInfo,
getDragOverrides: () => ({}),
+ getEffectDragOverrides: () => ({}),
codeValues,
}),
[codeValues, nodePathInfo, sequence],
diff --git a/packages/studio/src/helpers/timeline-layout.ts b/packages/studio/src/helpers/timeline-layout.ts
index b9ce6a98e1..53598bc26b 100644
--- a/packages/studio/src/helpers/timeline-layout.ts
+++ b/packages/studio/src/helpers/timeline-layout.ts
@@ -11,6 +11,7 @@ import {
} from '@remotion/studio-shared';
import type {
GetDragOverrides,
+ GetEffectDragOverrides,
SequenceSchema as SequenceSchemaShape,
TSequence,
} from 'remotion';
@@ -72,11 +73,13 @@ export const buildTimelineTree = ({
sequence,
nodePathInfo,
getDragOverrides,
+ getEffectDragOverrides,
codeValues,
}: {
sequence: TSequence;
nodePathInfo: SequenceNodePathInfo;
getDragOverrides: GetDragOverrides;
+ getEffectDragOverrides: GetEffectDragOverrides;
codeValues: CodeValues;
}): TimelineTreeNode[] => {
const roots: TimelineTreeNode[] = [];
@@ -119,7 +122,13 @@ export const buildTimelineTree = ({
label: 'Effects',
effectInfo: null,
children: sequence.effects.map((effect, i): TimelineTreeNode => {
- const effectFields = getEffectFieldsToShow(effect, i);
+ const effectFields = getEffectFieldsToShow({
+ effect,
+ effectIndex: i,
+ nodePath: sequenceSubscriptionKey,
+ codeValues,
+ getEffectDragOverrides,
+ });
return {
kind: 'group',
nodePathInfo: {
@@ -215,6 +224,7 @@ export const getExpandedTrackHeight = ({
nodePathInfo,
// We assume that no drag overrides can change the timeline layout
getDragOverrides: () => ({}),
+ getEffectDragOverrides: () => ({}),
codeValues,
});
const flat = flattenVisibleTreeNodes({nodes: tree, getIsExpanded});