🎥 Make videos programmatically with React
make it a draft pr
Jonny Burger8faaa375cde5
diff --git a/packages/example/remotion.config.ts b/packages/example/remotion.config.tsindex 19ac95b656..59f2c09b2e 100644--- a/packages/example/remotion.config.ts+++ b/packages/example/remotion.config.ts@@ -11,4 +11,3 @@ Config.overrideWebpackConfig(async (config) => {Config.setExperimentalClientSideRenderingEnabled(true);Config.setExperimentalVisualMode(true);-Config.setExperimentalRspackEnabled(true);diff --git a/packages/example/src/LightLeak/index.tsx b/packages/example/src/LightLeak/index.tsxindex ff3f799d24..0bbea707cc 100644--- a/packages/example/src/LightLeak/index.tsx+++ b/packages/example/src/LightLeak/index.tsx@@ -5,7 +5,7 @@ import {AbsoluteFill} from 'remotion';export const LightLeakExample: React.FC = () => {return (<AbsoluteFill style={{backgroundColor: 'black'}}>- <LightLeak durationInFrames={60} seed={3} hueShift={30} />+ <LightLeak durationInFrames={60} seed={1 + 2} hueShift={30} /><LightLeak durationInFrames={60} seed={3} hueShift={30} /></AbsoluteFill>);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 8a3dae6591..5efb5eb184 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@@ -1,6 +1,14 @@import {readFileSync} from 'node:fs';import path from 'node:path';-import type {File} from '@babel/types';+import type {+ Expression,+ File,+ JSXAttribute,+ JSXOpeningElement,+ ObjectExpression,+ ObjectProperty,+ UnaryExpression,+} from '@babel/types';import type {CanUpdateSequencePropsRequest,CanUpdateSequencePropsResponse,@@ -9,14 +17,103 @@ import * as recast from 'recast';import {parseAst} from '../../codemods/parse-ast';import type {ApiHandler} from '../api-types';-const findJsxElementAtLine = (ast: File, targetLine: number): boolean => {- let found = false;+type CanUpdatePropStatus =+ | {canUpdate: true}+ | {canUpdate: false; reason: 'computed'};++export const isStaticValue = (node: Expression): boolean => {+ switch (node.type) {+ case 'NumericLiteral':+ case 'StringLiteral':+ case 'BooleanLiteral':+ case 'NullLiteral':+ return true;+ case 'UnaryExpression':+ return (+ ((node as UnaryExpression).operator === '-' ||+ (node as UnaryExpression).operator === '+') &&+ (node as UnaryExpression).argument.type === 'NumericLiteral'+ );+ case 'ArrayExpression':+ return (node as Extract<Expression, {type: 'ArrayExpression'}>).elements.every(+ (el) =>+ el !== null &&+ el.type !== 'SpreadElement' &&+ isStaticValue(el),+ );+ case 'ObjectExpression':+ return (node as ObjectExpression).properties.every(+ (prop) =>+ prop.type === 'ObjectProperty' &&+ isStaticValue((prop as ObjectProperty).value as Expression),+ );+ default:+ return false;+ }+};++const getPropsStatus = (+ jsxElement: JSXOpeningElement,+): Record<string, CanUpdatePropStatus> => {+ const props: Record<string, CanUpdatePropStatus> = {};++ for (const attr of jsxElement.attributes) {+ if (attr.type === 'JSXSpreadAttribute') {+ continue;+ }++ if (attr.name.type === 'JSXNamespacedName') {+ continue;+ }++ const name = attr.name.name;+ if (typeof name !== 'string') {+ continue;+ }++ const {value} = attr as JSXAttribute;++ if (!value) {+ props[name] = {canUpdate: true};+ continue;+ }++ if (value.type === 'StringLiteral') {+ props[name] = {canUpdate: true};+ continue;+ }++ if (value.type === 'JSXExpressionContainer') {+ const {expression} = value;+ if (+ expression.type === 'JSXEmptyExpression' ||+ !isStaticValue(expression)+ ) {+ props[name] = {canUpdate: false, reason: 'computed'};+ continue;+ }++ props[name] = {canUpdate: true};+ continue;+ }++ props[name] = {canUpdate: false, reason: 'computed'};+ }++ return props;+};++const findJsxElementAtLine = (+ ast: File,+ targetLine: number,+): JSXOpeningElement | null => {+ let found: JSXOpeningElement | null = null;recast.types.visit(ast, {visitJSXOpeningElement(nodePath) {const {node} = nodePath;if (node.loc && node.loc.start.line === targetLine) {- found = true;+ found = node as unknown as JSXOpeningElement;return false;}@@ -30,7 +127,7 @@ const findJsxElementAtLine = (ast: File, targetLine: number): boolean => {export const canUpdateSequencePropsHandler: ApiHandler<CanUpdateSequencePropsRequest,CanUpdateSequencePropsResponse-> = ({input: {fileName, line, column: _column}, remotionRoot}) => {+> = ({input: {fileName, line, column: _column, keys}, remotionRoot}) => {try {const absolutePath = path.resolve(remotionRoot, fileName);const fileRelativeToRoot = path.relative(remotionRoot, absolutePath);@@ -41,14 +138,25 @@ export const canUpdateSequencePropsHandler: ApiHandler<const fileContents = readFileSync(absolutePath, 'utf-8');const ast = parseAst(fileContents);- const found = findJsxElementAtLine(ast, line);+ const jsxElement = findJsxElementAtLine(ast, line);- if (!found) {+ if (!jsxElement) {throw new Error('Could not find a JSX element at the specified location');}+ const allProps = getPropsStatus(jsxElement);+ const filteredProps: Record<string, CanUpdatePropStatus> = {};+ for (const key of keys) {+ if (key in allProps) {+ filteredProps[key] = allProps[key];+ } else {+ filteredProps[key] = {canUpdate: false, reason: 'computed'};+ }+ }+return Promise.resolve({canUpdate: true as const,+ props: filteredProps,});} catch (err) {return Promise.resolve({diff --git a/packages/studio-server/src/test/snapshots/light-leak-computed.txt b/packages/studio-server/src/test/snapshots/light-leak-computed.txtnew file mode 100644index 0000000000..d19ceb2fa2--- /dev/null+++ b/packages/studio-server/src/test/snapshots/light-leak-computed.txt@@ -0,0 +1,11 @@+import {LightLeak} from "@remotion/light-leaks";+import React from "react";+import {AbsoluteFill} from "remotion";++export const LightLeakExample: React.FC = () => {+ return (+ <AbsoluteFill style={{backgroundColor: "black"}}>+ <LightLeak durationInFrames={60} seed={1 + 2} hueShift={30} />+ </AbsoluteFill>+ );+};diff --git a/packages/studio-server/src/test/update-sequence-props.test.ts b/packages/studio-server/src/test/update-sequence-props.test.tsnew file mode 100644index 0000000000..af129f6862--- /dev/null+++ b/packages/studio-server/src/test/update-sequence-props.test.ts@@ -0,0 +1,74 @@+import {expect, test} from 'bun:test';+import type {IncomingMessage, ServerResponse} from 'node:http';+import path from 'node:path';+import type {Expression} from '@babel/types';+import {parseAst} from '../codemods/parse-ast';+import type {QueueMethods} from '../preview-server/api-types';+import {isStaticValue} from '../preview-server/routes/can-update-sequence-props';++const parseExpression = (code: string): Expression => {+ const ast = parseAst(`a = ${code}`);+ const stmt = ast.program.body[0];+ if (+ stmt.type !== 'ExpressionStatement' ||+ stmt.expression.type !== 'AssignmentExpression'+ ) {+ throw new Error('Unexpected AST');+ }++ return stmt.expression.right;+};++test('Static values should be detected as static', () => {+ expect(isStaticValue(parseExpression('42'))).toBe(true);+ expect(isStaticValue(parseExpression('"hello"'))).toBe(true);+ expect(isStaticValue(parseExpression('true'))).toBe(true);+ expect(isStaticValue(parseExpression('false'))).toBe(true);+ expect(isStaticValue(parseExpression('null'))).toBe(true);+ expect(isStaticValue(parseExpression('-1'))).toBe(true);+ expect(isStaticValue(parseExpression('[1, 2, 3]'))).toBe(true);+ expect(isStaticValue(parseExpression('{a: 1, b: "c"}'))).toBe(true);+ expect(isStaticValue(parseExpression('[]'))).toBe(true);+ expect(isStaticValue(parseExpression('{}'))).toBe(true);+});++test('Computed values should be detected as computed', () => {+ expect(isStaticValue(parseExpression('1 + 2'))).toBe(false);+ expect(isStaticValue(parseExpression('Math.random()'))).toBe(false);+ expect(isStaticValue(parseExpression('someVar'))).toBe(false);+ expect(isStaticValue(parseExpression('foo()'))).toBe(false);+ expect(isStaticValue(parseExpression('a ? b : c'))).toBe(false);+ expect(isStaticValue(parseExpression('`template ${"x"}`'))).toBe(false);+});++test('canUpdateSequenceProps should flag computed props', async () => {+ const {canUpdateSequencePropsHandler} = await import(+ '../preview-server/routes/can-update-sequence-props'+ );++ const result = await canUpdateSequencePropsHandler({+ input: {+ fileName: path.join(__dirname, 'snapshots', 'light-leak-computed.txt'),+ line: 8,+ column: 0,+ keys: ['durationInFrames', 'seed', 'hueShift'],+ },+ remotionRoot: '/',+ entryPoint: '',+ request: {} as IncomingMessage,+ response: {} as ServerResponse,+ logLevel: 'info',+ methods: {} as QueueMethods,+ publicDir: '',+ binariesDirectory: null,+ });++ expect(result.canUpdate).toBe(true);+ if (!result.canUpdate) {+ throw new Error('Expected canUpdate to be true');+ }++ expect(result.props.durationInFrames).toEqual({canUpdate: true});+ expect(result.props.hueShift).toEqual({canUpdate: true});+ expect(result.props.seed).toEqual({canUpdate: false, reason: 'computed'});+});diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex 1404464091..df6d408951 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -195,11 +195,17 @@ export type CanUpdateSequencePropsRequest = {fileName: string;line: number;column: number;+ keys: string[];};+export type CanUpdateSequencePropStatus =+ | {canUpdate: true}+ | {canUpdate: false; reason: 'computed'};+export type CanUpdateSequencePropsResponse =| {canUpdate: true;+ props: Record<string, CanUpdateSequencePropStatus>;}| {canUpdate: false;diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex 0461818e2e..33ecfc2e8d 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -8,6 +8,7 @@ export {ApplyVisualControlResponse,CanUpdateDefaultPropsRequest,CanUpdateDefaultPropsResponse,+ CanUpdateSequencePropStatus,CanUpdateSequencePropsRequest,CanUpdateSequencePropsResponse,CancelRenderRequest,diff --git a/packages/studio/src/components/Timeline/TimelineExpandedSection.tsx b/packages/studio/src/components/Timeline/TimelineExpandedSection.tsxindex 7f829a1d29..3c54dacafe 100644--- a/packages/studio/src/components/Timeline/TimelineExpandedSection.tsx+++ b/packages/studio/src/components/Timeline/TimelineExpandedSection.tsx@@ -1,3 +1,4 @@+import type {CanUpdateSequencePropStatus} from '@remotion/studio-shared';import React, {useCallback, useEffect, useMemo, useState} from 'react';import type {TSequence} from 'remotion';import type {OriginalPosition} from '../../error-overlay/react-overlay/utils/get-source-map';@@ -35,7 +36,15 @@ export const TimelineExpandedSection: React.FC<{readonly sequence: TSequence;readonly originalLocation: OriginalPosition | null;}> = ({sequence, originalLocation}) => {- const [canUpdate, setCanUpdate] = useState<boolean | null>(null);+ const [propStatuses, setPropStatuses] = useState<Record<+ string,+ CanUpdateSequencePropStatus+ > | null>(null);++ const schemaFields = useMemo(+ () => getSchemaFields(sequence.controls),+ [sequence.controls],+ );const validatedLocation = useMemo(() => {if (@@ -54,8 +63,8 @@ export const TimelineExpandedSection: React.FC<{}, [originalLocation]);useEffect(() => {- if (!sequence.controls || !validatedLocation) {- setCanUpdate(false);+ if (!sequence.controls || !validatedLocation || !schemaFields) {+ setPropStatuses(null);return;}@@ -63,19 +72,19 @@ export const TimelineExpandedSection: React.FC<{fileName: validatedLocation.source,line: validatedLocation.line,column: validatedLocation.column,+ keys: schemaFields.map((f) => f.key),}).then((result) => {- setCanUpdate(result.canUpdate);+ if (result.canUpdate) {+ setPropStatuses(result.props);+ } else {+ setPropStatuses(null);+ }}).catch(() => {- setCanUpdate(false);+ setPropStatuses(null);});- }, [sequence.controls, validatedLocation]);-- const schemaFields = useMemo(- () => getSchemaFields(sequence.controls),- [sequence.controls],- );+ }, [sequence.controls, validatedLocation, schemaFields]);const expandedHeight = useMemo(() => getExpandedTrackHeight(sequence.controls),@@ -84,7 +93,12 @@ export const TimelineExpandedSection: React.FC<{const onSave = useCallback((key: string, value: unknown) => {- if (!canUpdate || !validatedLocation) {+ if (!propStatuses || !validatedLocation) {+ return;+ }++ const status = propStatuses[key];+ if (!status || !status.canUpdate) {return;}@@ -100,7 +114,7 @@ export const TimelineExpandedSection: React.FC<{console.error('Failed to save sequence prop:', err);});},- [canUpdate, validatedLocation],+ [propStatuses, validatedLocation],);return (@@ -111,7 +125,7 @@ export const TimelineExpandedSection: React.FC<{<span style={fieldName}>{field.key}</span><TimelineFieldValuefield={field}- canUpdate={canUpdate}+ propStatus={propStatuses?.[field.key] ?? null}onSave={onSave}/></div>diff --git a/packages/studio/src/components/Timeline/TimelineSchemaField.tsx b/packages/studio/src/components/Timeline/TimelineSchemaField.tsxindex 24af4dee52..86fbf5b46c 100644--- a/packages/studio/src/components/Timeline/TimelineSchemaField.tsx+++ b/packages/studio/src/components/Timeline/TimelineSchemaField.tsx@@ -1,3 +1,4 @@+import type {CanUpdateSequencePropStatus} from '@remotion/studio-shared';import React, {useCallback} from 'react';import type {SchemaFieldInfo} from '../../helpers/timeline-layout';import {InputDragger} from '../NewComposition/InputDragger';@@ -27,7 +28,7 @@ const notEditableBackground: React.CSSProperties = {const TimelineNumberField: React.FC<{readonly field: SchemaFieldInfo;- readonly canUpdate: boolean | null;+ readonly canUpdate: boolean;readonly onSave: (key: string, value: unknown) => void;}> = ({field, canUpdate, onSave}) => {const onValueChange = useCallback((_newVal: number) => {@@ -74,34 +75,43 @@ const TimelineNumberField: React.FC<{export const TimelineFieldValue: React.FC<{readonly field: SchemaFieldInfo;- readonly canUpdate: boolean | null;+ readonly propStatus: CanUpdateSequencePropStatus | null;readonly onSave: (key: string, value: unknown) => void;-}> = ({field, canUpdate, onSave}) => {- const wrapperStyle: React.CSSProperties | undefined =- canUpdate === null || canUpdate === false- ? notEditableBackground- : undefined;+}> = ({field, propStatus, onSave}) => {+ const canUpdate = propStatus !== null && propStatus.canUpdate;if (!field.supported) {return (- <span style={{...unsupportedLabel, ...wrapperStyle}}>unsupported</span>+ <span style={unsupportedLabel}>unsupported</span>);}- if (field.typeName === 'number') {+ if (propStatus !== null && !propStatus.canUpdate) {+ return (+ <span style={unsupportedLabel}>{propStatus.reason}</span>+ );+ }++ if (propStatus === null) {return (- <span style={wrapperStyle}>- <TimelineNumberField- field={field}- canUpdate={canUpdate}- onSave={onSave}- />+ <span style={{...notEditableBackground}}>+ <span style={unsupportedLabel}>error</span></span>);}+ if (field.typeName === 'number') {+ return (+ <TimelineNumberField+ field={field}+ canUpdate={canUpdate}+ onSave={onSave}+ />+ );+ }+return (- <span style={{...unsupportedLabel, fontStyle: 'normal', ...wrapperStyle}}>+ <span style={{...unsupportedLabel, fontStyle: 'normal'}}>{String(field.currentValue)}</span>);