Skip to content

🎥 Make videos programmatically with React

Add save-sequence-props endpoint and extract timeline field components

Jonny Burger641bd25b028d
diff --git a/packages/studio-server/src/codemods/update-sequence-props.ts b/packages/studio-server/src/codemods/update-sequence-props.ts
new file mode 100644
index 0000000000..e688180c78
--- /dev/null
+++ b/packages/studio-server/src/codemods/update-sequence-props.ts
@@ -0,0 +1,100 @@
+import type {AssignmentExpression, ExpressionStatement} from '@babel/types';
+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';
+
+export const updateSequenceProps = async ({
+ input,
+ targetLine,
+ key,
+ value,
+ enumPaths,
+}: {
+ input: string;
+ targetLine: number;
+ key: string;
+ value: unknown;
+ enumPaths: EnumPath[];
+}): Promise<string> => {
+ const ast = parseAst(input);
+ let found = false;
+
+ recast.types.visit(ast, {
+ visitJSXOpeningElement(path) {
+ const {node} = path;
+
+ if (!node.loc || node.loc.start.line !== targetLine) {
+ return this.traverse(path);
+ }
+
+ const attr = node.attributes?.find((a) => {
+ if (a.type === 'JSXSpreadAttribute') {
+ return false;
+ }
+
+ if (a.name.type === 'JSXNamespacedName') {
+ return false;
+ }
+
+ return a.name.name === key;
+ });
+
+ if (!attr || attr.type === 'JSXSpreadAttribute') {
+ throw new Error(`Could not find attribute "${key}" on the JSX element`);
+ }
+
+ const parsed = (
+ (
+ parseAst(`a = ${stringifyDefaultProps({props: value, enumPaths})}`)
+ .program.body[0] as unknown as ExpressionStatement
+ ).expression as AssignmentExpression
+ ).right as ExpressionKind;
+
+ attr.value = recast.types.builders.jsxExpressionContainer(parsed);
+ found = true;
+
+ return this.traverse(path);
+ },
+ });
+
+ if (!found) {
+ throw new Error(
+ 'Could not find a JSX element at the specified line to update',
+ );
+ }
+
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
+ type PrettierType = typeof import('prettier');
+ let prettier: PrettierType | null = null;
+
+ try {
+ prettier = await import('prettier');
+ } catch {
+ throw new Error('Prettier cannot be found in the current project.');
+ }
+
+ const {format, resolveConfig, resolveConfigFile} = prettier as PrettierType;
+
+ const configFilePath = await resolveConfigFile();
+ if (!configFilePath) {
+ throw new Error('The Prettier config file was not found');
+ }
+
+ const prettierConfig = await resolveConfig(configFilePath);
+ if (!prettierConfig) {
+ throw new Error(
+ 'The Prettier config file was not found. For this feature, the "prettier" package must be installed and a .prettierrc file must exist.',
+ );
+ }
+
+ const finalFile = serializeAst(ast);
+
+ const prettified = await format(finalFile, {
+ ...prettierConfig,
+ filepath: 'test.tsx',
+ plugins: [],
+ endOfLine: 'auto',
+ });
+ return prettified;
+};
diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.ts
index 200415d03c..f39b048678 100644
--- a/packages/studio-server/src/preview-server/api-routes.ts
+++ b/packages/studio-server/src/preview-server/api-routes.ts
@@ -4,6 +4,7 @@ import {handleAddRender} from './routes/add-render';
import {applyCodemodHandler} from './routes/apply-codemod';
import {applyVisualControlHandler} from './routes/apply-visual-control-change';
import {canUpdateDefaultPropsHandler} from './routes/can-update-default-props';
+import {canUpdateSequencePropsHandler} from './routes/can-update-sequence-props';
import {handleCancelRender} from './routes/cancel-render';
import {deleteStaticFileHandler} from './routes/delete-static-file';
import {handleInstallPackage} from './routes/install-dependency';
@@ -11,6 +12,7 @@ import {handleOpenInFileExplorer} from './routes/open-in-file-explorer';
import {projectInfoHandler} from './routes/project-info';
import {handleRemoveRender} from './routes/remove-render';
import {handleRestartStudio} from './routes/restart-studio';
+import {saveSequencePropsHandler} from './routes/save-sequence-props';
import {subscribeToFileExistence} from './routes/subscribe-to-file-existence';
import {unsubscribeFromFileExistence} from './routes/unsubscribe-from-file-existence';
import {handleUpdate} from './routes/update-available';
@@ -32,6 +34,8 @@ export const allApiRoutes: {
'/api/apply-visual-control-change': applyVisualControlHandler,
'/api/apply-codemod': applyCodemodHandler,
'/api/can-update-default-props': canUpdateDefaultPropsHandler,
+ '/api/can-update-sequence-props': canUpdateSequencePropsHandler,
+ '/api/save-sequence-props': saveSequencePropsHandler,
'/api/update-available': handleUpdate,
'/api/project-info': projectInfoHandler,
'/api/delete-static-file': deleteStaticFileHandler,
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.ts
new file mode 100644
index 0000000000..031970a748
--- /dev/null
+++ b/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts
@@ -0,0 +1,79 @@
+import type {
+ CanUpdateSequencePropsRequest,
+ CanUpdateSequencePropsResponse,
+} from '@remotion/studio-shared';
+import {readFileSync} from 'node:fs';
+import path from 'node:path';
+import {parseAst} from '../../codemods/parse-ast';
+import type {ApiHandler} from '../api-types';
+import {checkIfTypeScriptFile} from './can-update-default-props';
+
+const findJsxElementAtLine = (
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ node: any,
+ targetLine: number,
+): boolean => {
+ if (!node || typeof node !== 'object') {
+ return false;
+ }
+
+ if (node.type === 'JSXOpeningElement' && node.loc) {
+ if (node.loc.start.line === targetLine) {
+ return true;
+ }
+ }
+
+ for (const key of Object.keys(node)) {
+ if (key === 'loc' || key === 'start' || key === 'end' || key === 'type') {
+ continue;
+ }
+
+ const child = node[key];
+ if (Array.isArray(child)) {
+ for (const item of child) {
+ if (findJsxElementAtLine(item, targetLine)) {
+ return true;
+ }
+ }
+ } else if (child && typeof child === 'object' && child.type) {
+ if (findJsxElementAtLine(child, targetLine)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+};
+
+export const canUpdateSequencePropsHandler: ApiHandler<
+ CanUpdateSequencePropsRequest,
+ CanUpdateSequencePropsResponse
+> = ({input: {fileName, line, column: _column}, remotionRoot}) => {
+ try {
+ const absolutePath = path.resolve(remotionRoot, fileName);
+ const fileRelativeToRoot = path.relative(remotionRoot, absolutePath);
+ if (fileRelativeToRoot.startsWith('..')) {
+ throw new Error('Cannot read a file outside the project');
+ }
+
+ checkIfTypeScriptFile(absolutePath);
+
+ const fileContents = readFileSync(absolutePath, 'utf-8');
+ const ast = parseAst(fileContents);
+
+ const found = findJsxElementAtLine(ast, line);
+
+ if (!found) {
+ throw new Error('Could not find a JSX element at the specified location');
+ }
+
+ return Promise.resolve({
+ canUpdate: true as const,
+ });
+ } catch (err) {
+ return Promise.resolve({
+ canUpdate: false as const,
+ reason: (err as Error).message,
+ });
+ }
+};
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.ts
new file mode 100644
index 0000000000..44fdee3ce9
--- /dev/null
+++ b/packages/studio-server/src/preview-server/routes/save-sequence-props.ts
@@ -0,0 +1,48 @@
+import type {
+ SaveSequencePropsRequest,
+ SaveSequencePropsResponse,
+} from '@remotion/studio-shared';
+import {readFileSync, writeFileSync} from 'node:fs';
+import path from 'node:path';
+import {updateSequenceProps} from '../../codemods/update-sequence-props';
+import type {ApiHandler} from '../api-types';
+import {checkIfTypeScriptFile} from './can-update-default-props';
+
+export const saveSequencePropsHandler: ApiHandler<
+ SaveSequencePropsRequest,
+ SaveSequencePropsResponse
+> = async ({
+ input: {fileName, line, column: _column, key, value, enumPaths},
+ remotionRoot,
+}) => {
+ try {
+ const absolutePath = path.resolve(remotionRoot, fileName);
+ const fileRelativeToRoot = path.relative(remotionRoot, absolutePath);
+ if (fileRelativeToRoot.startsWith('..')) {
+ throw new Error('Cannot modify a file outside the project');
+ }
+
+ checkIfTypeScriptFile(absolutePath);
+
+ const fileContents = readFileSync(absolutePath, 'utf-8');
+
+ const updated = await updateSequenceProps({
+ input: fileContents,
+ targetLine: line,
+ key,
+ value: JSON.parse(value),
+ enumPaths,
+ });
+
+ writeFileSync(absolutePath, updated);
+
+ return {
+ success: true,
+ };
+ } catch (err) {
+ return {
+ success: false,
+ reason: (err as Error).message,
+ };
+ }
+};
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 9f390874e7..1404464091 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -191,6 +191,39 @@ export type CanUpdateDefaultPropsResponse =
reason: string;
};
+export type CanUpdateSequencePropsRequest = {
+ fileName: string;
+ line: number;
+ column: number;
+};
+
+export type CanUpdateSequencePropsResponse =
+ | {
+ canUpdate: true;
+ }
+ | {
+ canUpdate: false;
+ reason: string;
+ };
+
+export type SaveSequencePropsRequest = {
+ fileName: string;
+ line: number;
+ column: number;
+ key: string;
+ value: string;
+ enumPaths: EnumPath[];
+};
+
+export type SaveSequencePropsResponse =
+ | {
+ success: true;
+ }
+ | {
+ success: false;
+ reason: string;
+ };
+
export type UpdateAvailableRequest = {};
export type UpdateAvailableResponse = {
currentVersion: string;
@@ -238,6 +271,14 @@ export type ApiRoutes = {
CanUpdateDefaultPropsRequest,
CanUpdateDefaultPropsResponse
>;
+ '/api/can-update-sequence-props': ReqAndRes<
+ CanUpdateSequencePropsRequest,
+ CanUpdateSequencePropsResponse
+ >;
+ '/api/save-sequence-props': ReqAndRes<
+ SaveSequencePropsRequest,
+ SaveSequencePropsResponse
+ >;
'/api/update-available': ReqAndRes<
UpdateAvailableRequest,
UpdateAvailableResponse
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index 4827356a2a..0461818e2e 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -8,6 +8,8 @@ export {
ApplyVisualControlResponse,
CanUpdateDefaultPropsRequest,
CanUpdateDefaultPropsResponse,
+ CanUpdateSequencePropsRequest,
+ CanUpdateSequencePropsResponse,
CancelRenderRequest,
CancelRenderResponse,
CopyStillToClipboardRequest,
@@ -21,6 +23,8 @@ export {
RemoveRenderRequest,
RestartStudioRequest,
RestartStudioResponse,
+ SaveSequencePropsRequest,
+ SaveSequencePropsResponse,
SimpleDiff,
SubscribeToFileExistenceRequest,
SubscribeToFileExistenceResponse,
diff --git a/packages/studio/src/components/Timeline/TimelineExpandedSection.tsx b/packages/studio/src/components/Timeline/TimelineExpandedSection.tsx
new file mode 100644
index 0000000000..ce16e77359
--- /dev/null
+++ b/packages/studio/src/components/Timeline/TimelineExpandedSection.tsx
@@ -0,0 +1,129 @@
+import React, {useCallback, useEffect, useMemo, useState} from 'react';
+import type {TSequence} from 'remotion';
+import {TIMELINE_TRACK_SEPARATOR} from '../../helpers/colors';
+import {
+ getExpandedTrackHeight,
+ getSchemaFields,
+} from '../../helpers/timeline-layout';
+import {callApi} from '../call-api';
+import {TimelineFieldValue} from './TimelineSchemaField';
+import {getOriginalLocationFromStack} from './TimelineStack/get-stack';
+
+const expandedSectionBase: React.CSSProperties = {
+ color: 'white',
+ fontFamily: 'Arial, Helvetica, sans-serif',
+ fontSize: 12,
+ display: 'flex',
+ flexDirection: 'column',
+ paddingLeft: 28,
+ paddingRight: 10,
+ borderBottom: `1px solid ${TIMELINE_TRACK_SEPARATOR}`,
+};
+
+const fieldRow: React.CSSProperties = {
+ display: 'flex',
+ alignItems: 'center',
+ gap: 8,
+};
+
+const fieldName: React.CSSProperties = {
+ flex: 1,
+ fontSize: 12,
+};
+
+type OriginalLocation = {
+ source: string;
+ line: number;
+ column: number;
+};
+
+export const TimelineExpandedSection: React.FC<{
+ readonly sequence: TSequence;
+}> = ({sequence}) => {
+ const [canUpdate, setCanUpdate] = useState<boolean | null>(null);
+ const [originalLocation, setOriginalLocation] =
+ useState<OriginalLocation | null>(null);
+
+ useEffect(() => {
+ if (!sequence.stack || !sequence.controls) {
+ setCanUpdate(false);
+ return;
+ }
+
+ getOriginalLocationFromStack(sequence.stack, 'sequence')
+ .then((location) => {
+ if (!location || !location.source || !location.line) {
+ setCanUpdate(false);
+ return undefined;
+ }
+
+ setOriginalLocation({
+ source: location.source,
+ line: location.line,
+ column: location.column ?? 0,
+ });
+
+ return callApi('/api/can-update-sequence-props', {
+ fileName: location.source,
+ line: location.line,
+ column: location.column ?? 0,
+ });
+ })
+ .then((result) => {
+ if (result) {
+ setCanUpdate(result.canUpdate);
+ }
+ })
+ .catch(() => {
+ setCanUpdate(false);
+ });
+ }, [sequence.stack, sequence.controls]);
+
+ const schemaFields = useMemo(
+ () => getSchemaFields(sequence.controls),
+ [sequence.controls],
+ );
+
+ const expandedHeight = useMemo(
+ () => getExpandedTrackHeight(sequence.controls),
+ [sequence.controls],
+ );
+
+ const onSave = useCallback(
+ (key: string, value: unknown) => {
+ if (!canUpdate || !originalLocation) {
+ return;
+ }
+
+ callApi('/api/save-sequence-props', {
+ fileName: originalLocation.source,
+ line: originalLocation.line,
+ column: originalLocation.column,
+ key,
+ value: JSON.stringify(value),
+ enumPaths: [],
+ }).catch((err) => {
+ // eslint-disable-next-line no-console
+ console.error('Failed to save sequence prop:', err);
+ });
+ },
+ [canUpdate, originalLocation],
+ );
+
+ return (
+ <div style={{...expandedSectionBase, height: expandedHeight}}>
+ {schemaFields
+ ? schemaFields.map((field) => (
+ <div key={field.key} style={{...fieldRow, height: field.rowHeight}}>
+ <span style={fieldName}>{field.key}</span>
+ <TimelineFieldValue
+ field={field}
+ canUpdate={canUpdate}
+ onSave={onSave}
+ />
+ </div>
+ ))
+ : 'No schema'}
+ </div>
+ );
+};
diff --git a/packages/studio/src/components/Timeline/TimelineListItem.tsx b/packages/studio/src/components/Timeline/TimelineListItem.tsx
index 05ccd2dc09..ba4a2eaf31 100644
--- a/packages/studio/src/components/Timeline/TimelineListItem.tsx
+++ b/packages/studio/src/components/Timeline/TimelineListItem.tsx
@@ -2,20 +2,12 @@ import React, {useCallback, useContext, useMemo} from 'react';
import type {TSequence} from 'remotion';
import {Internals} from 'remotion';
import {TIMELINE_TRACK_SEPARATOR} from '../../helpers/colors';
-import type {SchemaFieldInfo} from '../../helpers/timeline-layout';
import {
- getExpandedTrackHeight,
- getSchemaFields,
getTimelineLayerHeight,
TIMELINE_ITEM_BORDER_BOTTOM,
} from '../../helpers/timeline-layout';
import {ExpandedTracksContext} from '../ExpandedTracksProvider';
-import {InputDragger} from '../NewComposition/InputDragger';
-import {
- getZodNumberMaximum,
- getZodNumberMinimum,
- getZodNumberStep,
-} from '../RenderModal/SchemaEditor/zod-number-constraints';
+import {TimelineExpandedSection} from './TimelineExpandedSection';
import {TimelineLayerEye} from './TimelineLayerEye';
import {TimelineStack} from './TimelineStack';
@@ -45,85 +37,6 @@ const arrowButton: React.CSSProperties = {
lineHeight: 1,
};
-const expandedSectionBase: React.CSSProperties = {
- color: 'white',
- fontFamily: 'Arial, Helvetica, sans-serif',
- fontSize: 12,
- display: 'flex',
- flexDirection: 'column',
- paddingLeft: 28,
- paddingRight: 10,
- borderBottom: `1px solid ${TIMELINE_TRACK_SEPARATOR}`,
-};
-
-const fieldRow: React.CSSProperties = {
- display: 'flex',
- alignItems: 'center',
- gap: 8,
-};
-
-const fieldName: React.CSSProperties = {
- flex: 1,
- fontSize: 12,
-};
-
-const unsupportedLabel: React.CSSProperties = {
- color: 'rgba(255, 255, 255, 0.4)',
- fontSize: 12,
- marginLeft: 'auto',
- fontStyle: 'italic',
-};
-
-const draggerStyle: React.CSSProperties = {
- width: 80,
- marginLeft: 'auto',
-};
-
-const TimelineNumberField: React.FC<{
- readonly field: SchemaFieldInfo;
-}> = ({field}) => {
- const onValueChange = useCallback((_newVal: number) => {
- // TODO: wire up value change
- }, []);
-
- const onTextChange = useCallback((_newVal: string) => {
- // TODO: wire up text change
- }, []);
-
- return (
- <InputDragger
- type="number"
- value={field.currentValue as number}
- style={draggerStyle}
- status="ok"
- onValueChange={onValueChange}
- onTextChange={onTextChange}
- min={getZodNumberMinimum(field.fieldSchema)}
- max={getZodNumberMaximum(field.fieldSchema)}
- step={getZodNumberStep(field.fieldSchema)}
- rightAlign
- />
- );
-};
-
-const TimelineFieldValue: React.FC<{
- readonly field: SchemaFieldInfo;
-}> = ({field}) => {
- if (!field.supported) {
- return <span style={unsupportedLabel}>unsupported</span>;
- }
-
- if (field.typeName === 'number') {
- return <TimelineNumberField field={field} />;
- }
-
- return (
- <span style={{...unsupportedLabel, fontStyle: 'normal'}}>
- {String(field.currentValue)}
- </span>
- );
-};
-
export const TimelineListItem: React.FC<{
readonly sequence: TSequence;
readonly nestedDepth: number;
@@ -139,16 +52,6 @@ export const TimelineListItem: React.FC<{
const isExpanded = expandedTracks[sequence.id] ?? false;
- const schemaFields = useMemo(
- () => getSchemaFields(sequence.controls),
- [sequence.controls],
- );
-
- const expandedHeight = useMemo(
- () => getExpandedTrackHeight(sequence.controls),
- [sequence.controls],
- );
-
const onToggleExpand = useCallback(() => {
toggleTrack(sequence.id);
}, [sequence.id, toggleTrack]);
@@ -231,19 +134,7 @@ export const TimelineListItem: React.FC<{
<TimelineStack sequence={sequence} isCompact={isCompact} />
</div>
{visualModeEnabled && isExpanded ? (
- <div style={{...expandedSectionBase, height: expandedHeight}}>
- {schemaFields
- ? schemaFields.map((field) => (
- <div
- key={field.key}
- style={{...fieldRow, height: field.rowHeight}}
- >
- <span style={fieldName}>{field.key}</span>
- <TimelineFieldValue field={field} />
- </div>
- ))
- : 'No schema'}
- </div>
+ <TimelineExpandedSection sequence={sequence} />
) : null}
</>
);
diff --git a/packages/studio/src/components/Timeline/TimelineSchemaField.tsx b/packages/studio/src/components/Timeline/TimelineSchemaField.tsx
new file mode 100644
index 0000000000..5ec453c221
--- /dev/null
+++ b/packages/studio/src/components/Timeline/TimelineSchemaField.tsx
@@ -0,0 +1,103 @@
+import React, {useCallback} from 'react';
+import type {SchemaFieldInfo} from '../../helpers/timeline-layout';
+import {InputDragger} from '../NewComposition/InputDragger';
+import {
+ getZodNumberMaximum,
+ getZodNumberMinimum,
+ getZodNumberStep,
+} from '../RenderModal/SchemaEditor/zod-number-constraints';
+
+const unsupportedLabel: React.CSSProperties = {
+ color: 'rgba(255, 255, 255, 0.4)',
+ fontSize: 12,
+ marginLeft: 'auto',
+ fontStyle: 'italic',
+};
+
+const draggerStyle: React.CSSProperties = {
+ width: 80,
+ marginLeft: 'auto',
+};
+
+const notEditableBackground: React.CSSProperties = {
+ backgroundColor: 'rgba(255, 0, 0, 0.2)',
+ borderRadius: 3,
+ padding: '0 4px',
+};
+
+const TimelineNumberField: React.FC<{
+ readonly field: SchemaFieldInfo;
+ readonly canUpdate: boolean | null;
+ readonly onSave: (key: string, value: unknown) => void;
+}> = ({field, canUpdate, onSave}) => {
+ const onValueChange = useCallback(
+ (newVal: number) => {
+ if (canUpdate) {
+ onSave(field.key, newVal);
+ }
+ },
+ [canUpdate, onSave, field.key],
+ );
+
+ const onTextChange = useCallback(
+ (newVal: string) => {
+ if (canUpdate) {
+ const parsed = Number(newVal);
+ if (!Number.isNaN(parsed)) {
+ onSave(field.key, parsed);
+ }
+ }
+ },
+ [canUpdate, onSave, field.key],
+ );
+
+ return (
+ <InputDragger
+ type="number"
+ value={field.currentValue as number}
+ style={draggerStyle}
+ status="ok"
+ onValueChange={onValueChange}
+ onTextChange={onTextChange}
+ min={getZodNumberMinimum(field.fieldSchema)}
+ max={getZodNumberMaximum(field.fieldSchema)}
+ step={getZodNumberStep(field.fieldSchema)}
+ rightAlign
+ />
+ );
+};
+
+export const TimelineFieldValue: React.FC<{
+ readonly field: SchemaFieldInfo;
+ readonly canUpdate: boolean | null;
+ readonly onSave: (key: string, value: unknown) => void;
+}> = ({field, canUpdate, onSave}) => {
+ const wrapperStyle: React.CSSProperties | undefined =
+ canUpdate === null || canUpdate === false
+ ? notEditableBackground
+ : undefined;
+
+ if (!field.supported) {
+ return (
+ <span style={{...unsupportedLabel, ...wrapperStyle}}>unsupported</span>
+ );
+ }
+
+ if (field.typeName === 'number') {
+ return (
+ <span style={wrapperStyle}>
+ <TimelineNumberField
+ field={field}
+ canUpdate={canUpdate}
+ onSave={onSave}
+ />
+ </span>
+ );
+ }
+
+ return (
+ <span style={{...unsupportedLabel, fontStyle: 'normal', ...wrapperStyle}}>
+ {String(field.currentValue)}
+ </span>
+ );
+};