π₯ Make videos programmatically with React
updates
JonnyBurger0108d2f4d018
diff --git a/packages/light-leaks/src/LightLeak.tsx b/packages/light-leaks/src/LightLeak.tsxindex 8e69bbc469..de425c2cb0 100644--- a/packages/light-leaks/src/LightLeak.tsx+++ b/packages/light-leaks/src/LightLeak.tsx@@ -240,6 +240,14 @@ const lightLeakSchema = {default: 0,description: 'Hue Shift',},+ 'style.opacity': {+ type: 'number',+ min: 0,+ max: 1,+ step: 0.01,+ default: 1,+ description: 'Opacity',+ },} as const satisfies SequenceSchema;export const LightLeak: React.FC<LightLeakProps> = ({@@ -249,16 +257,21 @@ export const LightLeak: React.FC<LightLeakProps> = ({from: fromProp,...sequenceProps}) => {+ const styleProp = (sequenceProps as {style?: React.CSSProperties}).style;+ const opacityProp =+ typeof styleProp?.opacity === 'number' ? styleProp.opacity : 1;+const schemaInput = useMemo(() => {return {seed: seedProp,hueShift: hueShiftProp,+ 'style.opacity': opacityProp,};- }, [seedProp, hueShiftProp]);+ }, [seedProp, hueShiftProp, opacityProp]);const {controls,- values: {seed, hueShift},+ values: {seed, hueShift, 'style.opacity': opacity},} = Internals.useSchema(lightLeakSchema, schemaInput);const {durationInFrames: videoDuration} = useVideoConfig();@@ -287,6 +300,7 @@ export const LightLeak: React.FC<LightLeakProps> = ({name="<LightLeak>"controls={controls}{...sequenceProps}+ style={{...styleProp, opacity: opacity as number}}><LightLeakCanvas seed={seed} hueShift={hueShift} /></Sequence>diff --git a/packages/studio-server/src/codemods/update-nested-prop.ts b/packages/studio-server/src/codemods/update-nested-prop.tsnew file mode 100644index 0000000000..efe6e0b0d8--- /dev/null+++ b/packages/studio-server/src/codemods/update-nested-prop.ts@@ -0,0 +1,221 @@+import type {AssignmentExpression, ExpressionStatement} from '@babel/types';+import {stringifyDefaultProps, type EnumPath} from '@remotion/studio-shared';+import type {namedTypes} from 'ast-types';+import type {ExpressionKind} from 'ast-types/lib/gen/kinds';+import * as recast from 'recast';+import {parseAst} from './parse-ast';++const b = recast.types.builders;++const parseValueExpression = (+ value: unknown,+ enumPaths: EnumPath[],+): ExpressionKind => {+ return (+ (+ parseAst(`a = ${stringifyDefaultProps({props: value, enumPaths})}`)+ .program.body[0] as unknown as ExpressionStatement+ ).expression as AssignmentExpression+ ).right as ExpressionKind;+};++const findJsxAttribute = (+ attributes: (namedTypes.JSXAttribute | namedTypes.JSXSpreadAttribute)[],+ name: string,+): {attrIndex: number; attr: namedTypes.JSXAttribute | undefined} => {+ const attrIndex = attributes.findIndex((a) => {+ if (a.type === 'JSXSpreadAttribute') {+ return false;+ }++ if (a.name.type === 'JSXNamespacedName') {+ return false;+ }++ return a.name.name === name;+ });++ const found = attrIndex !== -1 ? attributes[attrIndex] : undefined;++ return {+ attrIndex,+ attr:+ found && found.type === 'JSXAttribute'+ ? (found as namedTypes.JSXAttribute)+ : undefined,+ };+};++const findObjectProperty = (+ objExpr: namedTypes.ObjectExpression,+ propertyName: string,+): {propIndex: number; prop: namedTypes.ObjectProperty | undefined} => {+ const propIndex = objExpr.properties.findIndex(+ (p) =>+ p.type === 'ObjectProperty' &&+ (((p as namedTypes.ObjectProperty).key.type === 'Identifier' &&+ ((p as namedTypes.ObjectProperty).key as namedTypes.Identifier)+ .name === propertyName) ||+ ((p as namedTypes.ObjectProperty).key.type === 'StringLiteral' &&+ (+ (p as namedTypes.ObjectProperty).key as namedTypes.StringLiteral+ ).value === propertyName)),+ );++ return {+ propIndex,+ prop:+ propIndex !== -1+ ? (objExpr.properties[propIndex] as namedTypes.ObjectProperty)+ : undefined,+ };+};++const getObjectExpression = (+ attr: namedTypes.JSXAttribute,+): namedTypes.ObjectExpression | null => {+ const {value} = attr;+ if (!value || value.type !== 'JSXExpressionContainer') {+ return null;+ }++ const container = value as namedTypes.JSXExpressionContainer;+ if (container.expression.type !== 'ObjectExpression') {+ return null;+ }++ return container.expression as namedTypes.ObjectExpression;+};++const getOldValueString = ({+ attr,+ childKey,+ defaultValue,+}: {+ attr: namedTypes.JSXAttribute | undefined;+ childKey: string;+ defaultValue: unknown | null;+}): string => {+ if (attr) {+ const objExpr = getObjectExpression(attr);+ if (objExpr) {+ const {prop} = findObjectProperty(objExpr, childKey);+ if (prop) {+ return recast.print(prop.value).code;+ }+ }+ }++ if (defaultValue !== null) {+ return JSON.stringify(defaultValue);+ }++ return '';+};++const removeNestedProp = ({+ attr,+ attrIndex,+ attributes,+ childKey,+}: {+ attr: namedTypes.JSXAttribute | undefined;+ attrIndex: number;+ attributes: (namedTypes.JSXAttribute | namedTypes.JSXSpreadAttribute)[];+ childKey: string;+}) => {+ if (!attr) {+ return;+ }++ const objExpr = getObjectExpression(attr);+ if (!objExpr) {+ return;+ }++ const {propIndex} = findObjectProperty(objExpr, childKey);+ if (propIndex !== -1) {+ objExpr.properties.splice(propIndex, 1);+ }++ if (objExpr.properties.length === 0 && attrIndex !== -1) {+ attributes.splice(attrIndex, 1);+ }+};++const setNestedProp = ({+ attr,+ attributes,+ parentKey,+ childKey,+ value,+ enumPaths,+}: {+ attr: namedTypes.JSXAttribute | undefined;+ attributes: (namedTypes.JSXAttribute | namedTypes.JSXSpreadAttribute)[];+ parentKey: string;+ childKey: string;+ value: unknown;+ enumPaths: EnumPath[];+}) => {+ const parsedValue = parseValueExpression(value, enumPaths);++ if (attr) {+ const objExpr = getObjectExpression(attr);+ if (objExpr) {+ const {prop} = findObjectProperty(objExpr, childKey);+ if (prop) {+ prop.value = parsedValue;+ } else {+ objExpr.properties.push(+ b.objectProperty(b.identifier(childKey), parsedValue),+ );+ }+ }+ } else {+ const objExpr = b.objectExpression([+ b.objectProperty(b.identifier(childKey), parsedValue),+ ]);+ const newAttr = b.jsxAttribute(+ b.jsxIdentifier(parentKey),+ b.jsxExpressionContainer(objExpr),+ );++ attributes.push(newAttr);+ }+};++export const updateNestedProp = ({+ node,+ parentKey,+ childKey,+ value,+ enumPaths,+ defaultValue,+ isDefault,+}: {+ node: namedTypes.JSXOpeningElement;+ parentKey: string;+ childKey: string;+ value: unknown;+ enumPaths: EnumPath[];+ defaultValue: unknown | null;+ isDefault: boolean;+}): string => {+ if (!node.attributes) {+ node.attributes = [];+ }++ const attributes = node.attributes;+ const {attrIndex, attr} = findJsxAttribute(attributes, parentKey);++ const oldValueString = getOldValueString({attr, childKey, defaultValue});++ if (isDefault) {+ removeNestedProp({attr, attrIndex, attributes, childKey});+ } else {+ setNestedProp({attr, attributes, parentKey, childKey, value, enumPaths});+ }++ return oldValueString;+};diff --git a/packages/studio-server/src/codemods/update-sequence-props.ts b/packages/studio-server/src/codemods/update-sequence-props.tsindex 3675e32f4a..b193c19540 100644--- a/packages/studio-server/src/codemods/update-sequence-props.ts+++ b/packages/studio-server/src/codemods/update-sequence-props.ts@@ -3,6 +3,21 @@ import {stringifyDefaultProps, type EnumPath} from '@remotion/studio-shared';import type {ExpressionKind} from 'ast-types/lib/gen/kinds';import * as recast from 'recast';import {parseAst, serializeAst} from './parse-ast';+import {updateNestedProp} from './update-nested-prop';++const b = recast.types.builders;++const parseValueExpression = (+ value: unknown,+ enumPaths: EnumPath[],+): ExpressionKind => {+ return (+ (+ parseAst(`a = ${stringifyDefaultProps({props: value, enumPaths})}`)+ .program.body[0] as unknown as ExpressionStatement+ ).expression as AssignmentExpression+ ).right as ExpressionKind;+};export const updateSequenceProps = ({input,@@ -27,6 +42,11 @@ export const updateSequenceProps = ({defaultValue !== null &&JSON.stringify(value) === JSON.stringify(defaultValue);+ const dotIndex = key.indexOf('.');+ const isNested = dotIndex !== -1;+ const parentKey = isNested ? key.slice(0, dotIndex) : key;+ const childKey = isNested ? key.slice(dotIndex + 1) : '';+recast.types.visit(ast, {visitJSXOpeningElement(path) {const {node} = path;@@ -35,6 +55,20 @@ export const updateSequenceProps = ({return this.traverse(path);}+ if (isNested) {+ oldValueString = updateNestedProp({+ node,+ parentKey,+ childKey,+ value,+ enumPaths,+ defaultValue,+ isDefault,+ });+ found = true;+ return this.traverse(path);+ }+const attrIndex = node.attributes?.findIndex((a) => {if (a.type === 'JSXSpreadAttribute') {return false;@@ -75,23 +109,13 @@ export const updateSequenceProps = ({return this.traverse(path);}- const parsed = (- (- parseAst(`a = ${stringifyDefaultProps({props: value, enumPaths})}`)- .program.body[0] as unknown as ExpressionStatement- ).expression as AssignmentExpression- ).right as ExpressionKind;+ const parsed = parseValueExpression(value, enumPaths);const newValue =- value === true- ? null- : recast.types.builders.jsxExpressionContainer(parsed);+ value === true ? null : b.jsxExpressionContainer(parsed);if (!attr || attr.type === 'JSXSpreadAttribute') {- const newAttr = recast.types.builders.jsxAttribute(- recast.types.builders.jsxIdentifier(key),- newValue,- );+ const newAttr = b.jsxAttribute(b.jsxIdentifier(key), newValue);if (!node.attributes) {node.attributes = [];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 12264fb199..d7a895ea45 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@@ -179,6 +179,57 @@ const findJsxElementAtLine = (return found;};+const getNestedPropStatus = (+ jsxElement: JSXOpeningElement,+ parentKey: string,+ childKey: string,+): CanUpdatePropStatus => {+ const attr = jsxElement.attributes.find(+ (a) =>+ a.type !== 'JSXSpreadAttribute' &&+ a.name.type !== 'JSXNamespacedName' &&+ a.name.name === parentKey,+ ) as JSXAttribute | undefined;++ if (!attr || !attr.value) {+ // Parent attribute doesn't exist, nested prop can be added+ return {canUpdate: true, codeValue: undefined};+ }++ if (attr.value.type !== 'JSXExpressionContainer') {+ return {canUpdate: false, reason: 'computed'};+ }++ const {expression} = attr.value;+ if (+ expression.type === 'JSXEmptyExpression' ||+ expression.type !== 'ObjectExpression'+ ) {+ // Parent is not an object literal (e.g. style={myStyles})+ return {canUpdate: false, reason: 'computed'};+ }++ const objExpr = expression as ObjectExpression;+ const prop = objExpr.properties.find(+ (p) =>+ p.type === 'ObjectProperty' &&+ ((p.key.type === 'Identifier' && p.key.name === childKey) ||+ (p.key.type === 'StringLiteral' && p.key.value === childKey)),+ ) as ObjectProperty | undefined;++ if (!prop) {+ // Property not set in the object, can be added+ return {canUpdate: true, codeValue: undefined};+ }++ const propValue = prop.value as Expression;+ if (!isStaticValue(propValue)) {+ return {canUpdate: false, reason: 'computed'};+ }++ return {canUpdate: true, codeValue: extractStaticValue(propValue)};+};+export const computeSequencePropsStatus = ({fileName,line,@@ -209,7 +260,14 @@ export const computeSequencePropsStatus = ({const allProps = getPropsStatus(jsxElement);const filteredProps: Record<string, CanUpdatePropStatus> = {};for (const key of keys) {- if (key in allProps) {+ const dotIndex = key.indexOf('.');+ if (dotIndex !== -1) {+ filteredProps[key] = getNestedPropStatus(+ jsxElement,+ key.slice(0, dotIndex),+ key.slice(dotIndex + 1),+ );+ } else if (key in allProps) {filteredProps[key] = allProps[key];} else {filteredProps[key] = {canUpdate: true, codeValue: undefined};diff --git a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts b/packages/studio-server/src/preview-server/routes/save-sequence-props.tsindex 0e94f723ad..0020479e38 100644--- a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts+++ b/packages/studio-server/src/preview-server/routes/save-sequence-props.ts@@ -13,7 +13,7 @@ import {suppressHmrForFile} from '../hmr-suppression';export const saveSequencePropsHandler: ApiHandler<SaveSequencePropsRequest,SaveSequencePropsResponse-> = async ({+> = ({input: {fileName, line, column, key, value, enumPaths, defaultValue},remotionRoot,logLevel,@@ -53,13 +53,13 @@ export const saveSequencePropsHandler: ApiHandler<),);- return {+ return Promise.resolve({success: true,- };+ } as const);} catch (err) {- return {+ return Promise.resolve({success: false,reason: (err as Error).message,- };+ } as const);}};diff --git a/packages/studio-server/src/test/snapshots/nested-props.txt b/packages/studio-server/src/test/snapshots/nested-props.txtnew file mode 100644index 0000000000..ff58d9842e--- /dev/null+++ b/packages/studio-server/src/test/snapshots/nested-props.txt@@ -0,0 +1,13 @@+import React from "react";+import {AbsoluteFill} from "remotion";++export const Example: React.FC = () => {+ return (+ <AbsoluteFill>+ <div style={{opacity: 0.5, scale: 2}} />+ <div style={{opacity: getOpacity(), scale: 2}} />+ <div style={dynamicStyles} />+ <div />+ </AbsoluteFill>+ );+};diff --git a/packages/studio-server/src/test/update-sequence-props.test.ts b/packages/studio-server/src/test/update-sequence-props.test.tsindex cb71f08c12..b9448876fb 100644--- a/packages/studio-server/src/test/update-sequence-props.test.ts+++ b/packages/studio-server/src/test/update-sequence-props.test.ts@@ -215,3 +215,214 @@ test('updateSequenceProps should throw for non-existent line', () => {}),).toThrow('Could not find a JSX element at the specified line to update');});++// --- Nested prop (dotted key) tests ---++const nestedInput = `import React from 'react';+import {AbsoluteFill} from 'remotion';++export const Example: React.FC = () => {+ return (+ <AbsoluteFill>+ <div style={{opacity: 0.5, scale: 2}} />+ <div />+ </AbsoluteFill>+ );+};+`;++test('updateSequenceProps should update a nested style property', () => {+ const {output, oldValueString} = updateSequenceProps({+ input: nestedInput,+ targetLine: 7,+ key: 'style.opacity',+ value: 0.8,+ enumPaths: [],+ defaultValue: null,+ });++ expect(oldValueString).toBe('0.5');+ expect(output).toContain('opacity: 0.8');+ expect(output).toContain('scale: 2');+});++test('updateSequenceProps should add a nested property to existing object', () => {+ const {output, oldValueString} = updateSequenceProps({+ input: nestedInput,+ targetLine: 7,+ key: 'style.rotate',+ value: 45,+ enumPaths: [],+ defaultValue: null,+ });++ expect(oldValueString).toBe('');+ expect(output).toContain('rotate: 45');+ // Existing properties should be preserved+ expect(output).toContain('opacity: 0.5');+ expect(output).toContain('scale: 2');+});++test('updateSequenceProps should create style attribute when it does not exist', () => {+ const {output, oldValueString} = updateSequenceProps({+ input: nestedInput,+ targetLine: 8,+ key: 'style.opacity',+ value: 0.3,+ enumPaths: [],+ defaultValue: null,+ });++ expect(oldValueString).toBe('');+ expect(output).toContain('style={{');+ expect(output).toContain('opacity: 0.3');+});++test('updateSequenceProps should remove nested property when value equals default', () => {+ const {output, oldValueString} = updateSequenceProps({+ input: nestedInput,+ targetLine: 7,+ key: 'style.opacity',+ value: 1,+ enumPaths: [],+ defaultValue: 1,+ });++ expect(oldValueString).toBe('0.5');+ expect(output).not.toContain('opacity');+ // Other properties should remain+ expect(output).toContain('scale: 2');+});++test('updateSequenceProps should remove entire style attribute when object becomes empty', () => {+ // First remove scale, leaving only opacity+ const singlePropInput = `import React from 'react';++export const Example: React.FC = () => {+ return <div style={{opacity: 0.5}} />;+};+`;++ const {output, oldValueString} = updateSequenceProps({+ input: singlePropInput,+ targetLine: 4,+ key: 'style.opacity',+ value: 1,+ enumPaths: [],+ defaultValue: 1,+ });++ expect(oldValueString).toBe('0.5');+ expect(output).not.toContain('style');+});++test('updateSequenceProps should report default as oldValueString for missing nested property', () => {+ const {oldValueString} = updateSequenceProps({+ input: nestedInput,+ targetLine: 8,+ key: 'style.opacity',+ value: 0.5,+ enumPaths: [],+ defaultValue: 1,+ });++ expect(oldValueString).toBe('1');+});++// --- computeSequencePropsStatus nested prop tests ---++test('computeSequencePropsStatus should detect static nested props', () => {+ const result = computeSequencePropsStatus({+ fileName: path.join(__dirname, 'snapshots', 'nested-props.txt'),+ line: 7,+ keys: ['style.opacity', 'style.scale'],+ remotionRoot: '/',+ });++ expect(result.canUpdate).toBe(true);+ if (!result.canUpdate) throw new Error('Expected canUpdate to be true');++ expect(result.props['style.opacity']).toEqual({+ canUpdate: true,+ codeValue: 0.5,+ });+ expect(result.props['style.scale']).toEqual({+ canUpdate: true,+ codeValue: 2,+ });+});++test('computeSequencePropsStatus should flag computed nested props', () => {+ const result = computeSequencePropsStatus({+ fileName: path.join(__dirname, 'snapshots', 'nested-props.txt'),+ line: 8,+ keys: ['style.opacity', 'style.scale'],+ remotionRoot: '/',+ });++ expect(result.canUpdate).toBe(true);+ if (!result.canUpdate) throw new Error('Expected canUpdate to be true');++ // opacity uses getOpacity() β computed+ expect(result.props['style.opacity']).toEqual({+ canUpdate: false,+ reason: 'computed',+ });+ // scale is static+ expect(result.props['style.scale']).toEqual({+ canUpdate: true,+ codeValue: 2,+ });+});++test('computeSequencePropsStatus should flag computed when parent is not an object', () => {+ const result = computeSequencePropsStatus({+ fileName: path.join(__dirname, 'snapshots', 'nested-props.txt'),+ line: 9,+ keys: ['style.opacity'],+ remotionRoot: '/',+ });++ expect(result.canUpdate).toBe(true);+ if (!result.canUpdate) throw new Error('Expected canUpdate to be true');++ // style={dynamicStyles} β entire parent is computed+ expect(result.props['style.opacity']).toEqual({+ canUpdate: false,+ reason: 'computed',+ });+});++test('computeSequencePropsStatus should report unset nested props as undefined', () => {+ const result = computeSequencePropsStatus({+ fileName: path.join(__dirname, 'snapshots', 'nested-props.txt'),+ line: 7,+ keys: ['style.rotate'],+ remotionRoot: '/',+ });++ expect(result.canUpdate).toBe(true);+ if (!result.canUpdate) throw new Error('Expected canUpdate to be true');++ expect(result.props['style.rotate']).toEqual({+ canUpdate: true,+ codeValue: undefined,+ });+});++test('computeSequencePropsStatus should report unset when parent attribute missing', () => {+ const result = computeSequencePropsStatus({+ fileName: path.join(__dirname, 'snapshots', 'nested-props.txt'),+ line: 10,+ keys: ['style.opacity'],+ remotionRoot: '/',+ });++ expect(result.canUpdate).toBe(true);+ if (!result.canUpdate) throw new Error('Expected canUpdate to be true');++ expect(result.props['style.opacity']).toEqual({+ canUpdate: true,+ codeValue: undefined,+ });+});