🎥 Make videos programmatically with React
`@remotion/studio`: Batch easing changes for selected keyframes (#9518)
Jonny Burger039bf42ac5c7
diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.tsindex 7bc2aef704..a4ceeab046 100644--- a/packages/studio-server/src/preview-server/api-routes.ts+++ b/packages/studio-server/src/preview-server/api-routes.ts@@ -7,6 +7,7 @@ import {handleAddRender} from './routes/add-render';import {addSequenceKeyframeHandler} from './routes/add-sequence-keyframe';import {applyCodemodHandler} from './routes/apply-codemod';import {applyVisualControlHandler} from './routes/apply-visual-control-change';+import {batchUpdateKeyframeSettingsHandler} from './routes/batch-update-keyframe-settings';import {handleCancelRender} from './routes/cancel-render';import {compositionComponentInfoHandler} from './routes/composition-component-info';import {convertFigmaClipboardToSvgHandler} from './routes/convert-figma-clipboard-to-svg';@@ -89,6 +90,7 @@ export const allApiRoutes: {'/api/update-sequence-keyframe-settings':updateSequenceKeyframeSettingsHandler,'/api/update-effect-keyframe-settings': updateEffectKeyframeSettingsHandler,+ '/api/batch-update-keyframe-settings': batchUpdateKeyframeSettingsHandler,'/api/delete-effect': deleteEffectHandler,'/api/paste-effects': pasteEffectsHandler,'/api/delete-jsx-node': deleteJsxNodeHandler,diff --git a/packages/studio-server/src/preview-server/routes/batch-update-keyframe-settings.ts b/packages/studio-server/src/preview-server/routes/batch-update-keyframe-settings.tsnew file mode 100644index 0000000000..242261ea55--- /dev/null+++ b/packages/studio-server/src/preview-server/routes/batch-update-keyframe-settings.ts@@ -0,0 +1,285 @@+import {readFileSync} from 'node:fs';+import type {LogLevel} from '@remotion/renderer';+import {RenderInternals} from '@remotion/renderer';+import type {+ BatchUpdateEffectKeyframeSettings,+ BatchUpdateKeyframeSettingsRequest,+ BatchUpdateKeyframeSettingsResponse,+ BatchUpdateSequenceKeyframeSettings,+ KeyframeSettings,+} from '@remotion/studio-shared';+import {+ updateEffectKeyframes,+ updateSequenceKeyframes,+} from '../../codemods/update-keyframes/update-keyframes';+import {writeFileAndNotifyFileWatchers} from '../../file-watcher';+import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';+import type {ApiHandler} from '../api-types';+import {+ printUndoHint,+ pushTransactionToUndoStack,+ suppressUndoStackInvalidation,+} from '../undo-stack';+import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';+import {logEffectUpdate} from './log-updates/log-effect-update';+import {logUpdate} from './log-updates/log-update';+import {withSourceFileWriteQueue} from './source-file-write-queue';++type ResolvedSequenceUpdate = BatchUpdateSequenceKeyframeSettings & {+ fileRelativeToRoot: string;+};++type ResolvedEffectUpdate = BatchUpdateEffectKeyframeSettings & {+ fileRelativeToRoot: string;+};++type FileGroup = {+ sequenceKeyframes: ResolvedSequenceUpdate[];+ effectKeyframes: ResolvedEffectUpdate[];+};++type UndoSnapshot = {+ filePath: string;+ oldContents: string;+ newContents: string;+ logLine: number;+};++type SequenceLog = {+ fileRelativeToRoot: string;+ line: number;+ key: string;+ oldValueString: string;+ newValueString: string;+ formatted: boolean;+};++type EffectLog = {+ fileRelativeToRoot: string;+ line: number;+ effectName: string;+ propKey: string;+ oldValueString: string;+ newValueString: string;+ formatted: boolean;+};++const groupBy = <T>(items: T[], getKey: (item: T) => string): T[][] => {+ const groups = new Map<string, T[]>();+ for (const item of items) {+ const key = getKey(item);+ const group = groups.get(key) ?? [];+ group.push(item);+ groups.set(key, group);+ }++ return [...groups.values()];+};++const toOperation = (settings: KeyframeSettings) =>+ settings.type === 'settings'+ ? {+ type: 'settings' as const,+ clamping: settings.clamping,+ posterize: settings.posterize,+ output: settings.output,+ }+ : {+ type: 'easing' as const,+ segmentIndex: settings.segmentIndex,+ easing: settings.easing,+ };++export const batchUpdateKeyframeSettings = async ({+ sequenceKeyframes,+ effectKeyframes,+ clientId,+ remotionRoot,+ logLevel,+}: BatchUpdateKeyframeSettingsRequest & {+ remotionRoot: string;+ logLevel: LogLevel;+}): Promise<void> => {+ const totalUpdates = sequenceKeyframes.length + effectKeyframes.length;+ if (totalUpdates === 0) {+ throw new Error('No keyframe settings updates were specified');+ }++ const fileGroups = new Map<string, FileGroup>();+ for (const update of sequenceKeyframes) {+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName: update.fileName,+ action: 'modify',+ });+ const group = fileGroups.get(absolutePath) ?? {+ sequenceKeyframes: [],+ effectKeyframes: [],+ };+ group.sequenceKeyframes.push({...update, fileRelativeToRoot});+ fileGroups.set(absolutePath, group);+ }++ for (const update of effectKeyframes) {+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName: update.fileName,+ action: 'modify',+ });+ const group = fileGroups.get(absolutePath) ?? {+ sequenceKeyframes: [],+ effectKeyframes: [],+ };+ group.effectKeyframes.push({...update, fileRelativeToRoot});+ fileGroups.set(absolutePath, group);+ }++ const snapshots: UndoSnapshot[] = [];+ const sequenceLogs: SequenceLog[] = [];+ const effectLogs: EffectLog[] = [];+ for (const [absolutePath, group] of fileGroups) {+ const fileContents = readFileSync(absolutePath, 'utf-8');+ let output = fileContents;+ let firstLogLine = Number.POSITIVE_INFINITY;++ for (const updates of groupBy(group.sequenceKeyframes, (update) =>+ JSON.stringify(update.nodePath.nodePath),+ )) {+ const firstUpdate = updates[0];+ const result = await updateSequenceKeyframes({+ input: output,+ nodePath: firstUpdate.nodePath.nodePath,+ schema: firstUpdate.schema,+ videoConfigValues: firstUpdate.nodePath.videoConfigValues,+ updates: updates.map((update) => ({+ key: update.key,+ operation: toOperation(update.settings),+ })),+ });+ output = result.output;+ firstLogLine = Math.min(firstLogLine, result.logLine);++ for (const [index, update] of updates.entries()) {+ sequenceLogs.push({+ fileRelativeToRoot: update.fileRelativeToRoot,+ line: result.logLine,+ key: update.key,+ oldValueString: result.oldValueStrings[index],+ newValueString: result.newValueStrings[index],+ formatted: result.formatted,+ });+ }+ }++ for (const updates of groupBy(+ group.effectKeyframes,+ (update) =>+ `${JSON.stringify(update.sequenceNodePath.nodePath)}:${+ update.effectIndex+ }`,+ )) {+ const firstUpdate = updates[0];+ const result = await updateEffectKeyframes({+ input: output,+ sequenceNodePath: firstUpdate.sequenceNodePath.nodePath,+ effectIndex: firstUpdate.effectIndex,+ schema: firstUpdate.schema,+ videoConfigValues: firstUpdate.sequenceNodePath.videoConfigValues,+ updates: updates.map((update) => ({+ key: update.key,+ operation: toOperation(update.settings),+ })),+ });+ output = result.output;+ firstLogLine = Math.min(firstLogLine, result.logLine);++ for (const [index, update] of updates.entries()) {+ effectLogs.push({+ fileRelativeToRoot: update.fileRelativeToRoot,+ line: result.logLine,+ effectName: result.effectCallee,+ propKey: update.key,+ oldValueString: result.oldValueStrings[index],+ newValueString: result.newValueStrings[index],+ formatted: result.formatted,+ });+ }+ }++ snapshots.push({+ filePath: absolutePath,+ oldContents: fileContents,+ newContents: output,+ logLine: Number.isFinite(firstLogLine) ? firstLogLine : 1,+ });+ }++ pushTransactionToUndoStack({+ snapshots,+ logLevel,+ remotionRoot,+ description:+ totalUpdates === 1+ ? {+ undoMessage: '↩️ Keyframe settings reverted',+ redoMessage: '↪️ Keyframe settings updated',+ }+ : {+ undoMessage: `↩️ ${totalUpdates} keyframe settings reverted`,+ redoMessage: `↪️ ${totalUpdates} keyframe settings updated`,+ },+ entryType: sequenceKeyframes.length > 0 ? 'sequence-props' : 'effect-props',+ suppressHmrOnFileRestore: true,+ });++ for (const snapshot of snapshots) {+ suppressUndoStackInvalidation(snapshot.filePath);+ suppressBundlerUpdateForFile(snapshot.filePath);+ writeFileAndNotifyFileWatchers(+ snapshot.filePath,+ snapshot.newContents,+ clientId,+ );+ }++ for (const log of sequenceLogs) {+ logUpdate({+ ...log,+ defaultValueString: null,+ logLevel,+ removedProps: [],+ addedProps: [],+ });+ }++ for (const log of effectLogs) {+ logEffectUpdate({+ ...log,+ defaultValueString: null,+ logLevel,+ removedProps: [],+ addedProps: [],+ });+ }++ printUndoHint(logLevel);+};++export const batchUpdateKeyframeSettingsHandler: ApiHandler<+ BatchUpdateKeyframeSettingsRequest,+ BatchUpdateKeyframeSettingsResponse+> = ({input, remotionRoot, logLevel}) =>+ withSourceFileWriteQueue(async () => {+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[batch-update-keyframe-settings] Received ${input.sequenceKeyframes.length + input.effectKeyframes.length} update(s)`,+ );++ await batchUpdateKeyframeSettings({+ ...input,+ remotionRoot,+ logLevel,+ });++ return {success: true};+ });diff --git a/packages/studio-server/src/test/batch-update-keyframe-settings.test.ts b/packages/studio-server/src/test/batch-update-keyframe-settings.test.tsnew file mode 100644index 0000000000..8b08cfa260--- /dev/null+++ b/packages/studio-server/src/test/batch-update-keyframe-settings.test.ts@@ -0,0 +1,141 @@+import {expect, test} from 'bun:test';+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';+import {tmpdir} from 'node:os';+import {join} from 'node:path';+import type {InteractivitySchema} from 'remotion';+import {NoReactInternals} from 'remotion/no-react';+import {+ createFileWatcherRegistry,+ setFileWatcherRegistry,+} from '../file-watcher';+import {setLiveEventsListener} from '../preview-server/live-events';+import {batchUpdateKeyframeSettings} from '../preview-server/routes/batch-update-keyframe-settings';+import {+ clearUndoStackForTests,+ getUndoStack,+ popRedo,+ popUndo,+} from '../preview-server/undo-stack';+import {lineColumnToNodePath} from './test-utils';++const input = `import {tint} from '@remotion/effects/tint';+import {AbsoluteFill, interpolate, useCurrentFrame} from 'remotion';++export const Comp = () => {+\tconst frame = useCurrentFrame();+\treturn (+\t\t<AbsoluteFill+\t\t\tstyle={{opacity: interpolate(frame, [0, 10, 20], [0, 0.5, 1])}}+\t\t\teffects={[tint({amount: interpolate(frame, [0, 20], [0.2, 0.8])})]}+\t\t/>+\t);+};+`;++const effectSchema = {+ amount: {+ type: 'number',+ default: 0,+ hiddenFromList: false,+ },+} satisfies InteractivitySchema;++test('batches sequence and effect easing changes into one undo entry', async () => {+ clearUndoStackForTests();+ const cleanupFileWatcher = setFileWatcherRegistry(+ createFileWatcherRegistry(),+ );+ const cleanupLiveEvents = setLiveEventsListener({+ addNewClientListener: () => () => undefined,+ closeConnections: () => Promise.resolve(),+ router: () => Promise.resolve(),+ sendEventToClient: () => undefined,+ sendEventToClientId: () => true,+ });+ const dir = mkdtempSync(join(tmpdir(), 'remotion-keyframe-settings-'));+ const sequenceFileName = 'SequenceComp.tsx';+ const effectFileName = 'EffectComp.tsx';+ const sequenceFilePath = join(dir, sequenceFileName);+ const effectFilePath = join(dir, effectFileName);+ const sequenceNodePath = {+ absolutePath: sequenceFileName,+ nodePath: lineColumnToNodePath(input, 7),+ sequenceKeys: ['style.opacity'],+ effectKeys: [['amount']],+ videoConfigValues: null,+ };+ const effectNodePath = {+ ...sequenceNodePath,+ absolutePath: effectFileName,+ };++ try {+ writeFileSync(sequenceFilePath, input);+ writeFileSync(effectFilePath, input);++ await batchUpdateKeyframeSettings({+ sequenceKeyframes: [+ {+ fileName: sequenceFileName,+ nodePath: sequenceNodePath,+ key: 'style.opacity',+ settings: {+ type: 'easing',+ segmentIndex: 0,+ easing: {type: 'bezier', x1: 0.42, y1: 0, x2: 1, y2: 1},+ },+ schema: NoReactInternals.sequenceSchema,+ },+ {+ fileName: sequenceFileName,+ nodePath: sequenceNodePath,+ key: 'style.opacity',+ settings: {+ type: 'easing',+ segmentIndex: 1,+ easing: {type: 'bezier', x1: 0, y1: 0, x2: 0.58, y2: 1},+ },+ schema: NoReactInternals.sequenceSchema,+ },+ ],+ effectKeyframes: [+ {+ fileName: effectFileName,+ sequenceNodePath: effectNodePath,+ effectIndex: 0,+ key: 'amount',+ settings: {+ type: 'easing',+ segmentIndex: 0,+ easing: {type: 'bezier', x1: 0.42, y1: 0, x2: 1, y2: 1},+ },+ schema: effectSchema,+ },+ ],+ clientId: 'test-client',+ remotionRoot: dir,+ logLevel: 'error',+ });++ const sequenceOutput = readFileSync(sequenceFilePath, 'utf-8');+ const effectOutput = readFileSync(effectFilePath, 'utf-8');+ expect(sequenceOutput).toContain(+ 'easing: [Easing.bezier(0.42, 0, 1, 1), Easing.bezier(0, 0, 0.58, 1)]',+ );+ expect(effectOutput).toContain('easing: [Easing.bezier(0.42, 0, 1, 1)]');+ expect(getUndoStack()).toHaveLength(1);++ expect(popUndo()).toEqual({success: true});+ expect(readFileSync(sequenceFilePath, 'utf-8')).toBe(input);+ expect(readFileSync(effectFilePath, 'utf-8')).toBe(input);++ expect(popRedo()).toEqual({success: true});+ expect(readFileSync(sequenceFilePath, 'utf-8')).toBe(sequenceOutput);+ expect(readFileSync(effectFilePath, 'utf-8')).toBe(effectOutput);+ } finally {+ clearUndoStackForTests();+ cleanupLiveEvents();+ cleanupFileWatcher();+ rmSync(dir, {force: true, recursive: true});+ }+});diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex e25fe5400a..27fbf301ae 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -597,6 +597,26 @@ export type UpdateEffectKeyframeSettingsRequest = {export type UpdateEffectKeyframeSettingsResponse = SaveEffectPropsResponse;+export type BatchUpdateSequenceKeyframeSettings = Omit<+ UpdateSequenceKeyframeSettingsRequest,+ 'clientId'+>;++export type BatchUpdateEffectKeyframeSettings = Omit<+ UpdateEffectKeyframeSettingsRequest,+ 'clientId'+>;++export type BatchUpdateKeyframeSettingsRequest = {+ sequenceKeyframes: BatchUpdateSequenceKeyframeSettings[];+ effectKeyframes: BatchUpdateEffectKeyframeSettings[];+ clientId: string;+};++export type BatchUpdateKeyframeSettingsResponse = {+ success: true;+};+type BaseDeleteEffectRequestItem = {fileName: string;sequenceNodePath: SequencePropsSubscriptionKey;@@ -969,6 +989,10 @@ export type ApiRoutes = {UpdateEffectKeyframeSettingsRequest,UpdateEffectKeyframeSettingsResponse>;+ '/api/batch-update-keyframe-settings': ReqAndRes<+ BatchUpdateKeyframeSettingsRequest,+ BatchUpdateKeyframeSettingsResponse+ >;'/api/delete-effect': ReqAndRes<DeleteEffectRequest, DeleteEffectResponse>;'/api/paste-effects': ReqAndRes<PasteEffectsRequest, PasteEffectsResponse>;'/api/delete-jsx-node': ReqAndRes<diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex 946f4e68a4..ccf6fecf30 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -14,6 +14,10 @@ export {ApplyCodemodResponse,ApplyVisualControlRequest,ApplyVisualControlResponse,+ BatchUpdateEffectKeyframeSettings,+ BatchUpdateKeyframeSettingsRequest,+ BatchUpdateKeyframeSettingsResponse,+ BatchUpdateSequenceKeyframeSettings,CanUpdateDefaultPropsResponse,CanUpdateSequencePropsRequest,CancelRenderRequest,diff --git a/packages/studio/src/components/Timeline/call-update-keyframe-settings.ts b/packages/studio/src/components/Timeline/call-update-keyframe-settings.tsindex 6815a7b7d2..bbe105c8e3 100644--- a/packages/studio/src/components/Timeline/call-update-keyframe-settings.ts+++ b/packages/studio/src/components/Timeline/call-update-keyframe-settings.ts@@ -5,6 +5,7 @@ import {} from '@remotion/studio-shared';import type {SequencePropsSubscriptionKey, InteractivitySchema} from 'remotion';import {callApi} from '../call-api';+import {showNotification} from '../Notifications/NotificationCenter';import {applyEffectResponseToPropStatuses} from './apply-effect-response-to-prop-statuses';import {enqueueSavePropChange} from './save-prop-queue';import type {SetPropStatuses} from './save-sequence-prop';@@ -92,3 +93,77 @@ export const callUpdateEffectKeyframeSettings = ({errorLabel: 'Could not update keyframe settings',});};++type BatchSequenceKeyframeSettingsUpdate = {+ fileName: string;+ nodePath: SequencePropsSubscriptionKey;+ fieldKey: string;+ settings: KeyframeSettings;+ schema: InteractivitySchema;+};++type BatchEffectKeyframeSettingsUpdate = BatchSequenceKeyframeSettingsUpdate & {+ effectIndex: number;+};++export const callBatchUpdateKeyframeSettings = ({+ sequenceKeyframes,+ effectKeyframes,+ setPropStatuses,+ clientId,+}: {+ sequenceKeyframes: BatchSequenceKeyframeSettingsUpdate[];+ effectKeyframes: BatchEffectKeyframeSettingsUpdate[];+ setPropStatuses: SetPropStatuses;+ clientId: string;+}): Promise<void> => {+ for (const update of sequenceKeyframes) {+ setPropStatuses(update.nodePath, (prev) =>+ optimisticUpdateSequenceKeyframeSettings({+ previous: prev,+ fieldKey: update.fieldKey,+ settings: update.settings,+ }),+ );+ }++ for (const update of effectKeyframes) {+ setPropStatuses(update.nodePath, (prev) =>+ optimisticUpdateEffectKeyframeSettings({+ previous: prev,+ effectIndex: update.effectIndex,+ fieldKey: update.fieldKey,+ settings: update.settings,+ }),+ );+ }++ return callApi('/api/batch-update-keyframe-settings', {+ sequenceKeyframes: sequenceKeyframes.map((update) => ({+ fileName: update.fileName,+ nodePath: update.nodePath,+ key: update.fieldKey,+ settings: update.settings,+ schema: update.schema,+ })),+ effectKeyframes: effectKeyframes.map((update) => ({+ fileName: update.fileName,+ sequenceNodePath: update.nodePath,+ effectIndex: update.effectIndex,+ key: update.fieldKey,+ settings: update.settings,+ schema: update.schema,+ })),+ clientId,+ })+ .then(() => undefined)+ .catch((err) => {+ showNotification(+ `Could not update keyframe settings: ${+ err instanceof Error ? err.message : String(err)+ }`,+ 4000,+ );+ throw err;+ });+};diff --git a/packages/studio/src/components/Timeline/update-selected-easing.ts b/packages/studio/src/components/Timeline/update-selected-easing.tsindex be7bb6db7c..a2f15b4778 100644--- a/packages/studio/src/components/Timeline/update-selected-easing.ts+++ b/packages/studio/src/components/Timeline/update-selected-easing.ts@@ -14,10 +14,7 @@ import type {TSequence,} from 'remotion';import {Internals} from 'remotion';-import {- callUpdateEffectKeyframeSettings,- callUpdateSequenceKeyframeSettings,-} from './call-update-keyframe-settings';+import {callBatchUpdateKeyframeSettings} from './call-update-keyframe-settings';import {findTrackForNodePathInfo} from './find-track-for-node-path-info';import {parseKeyframeFieldFromNodePath} from './parse-keyframe-field-from-node-path';import type {SetPropStatuses} from './save-sequence-prop';@@ -265,36 +262,35 @@ export const updateSelectedTimelineEasings = ({return null;}- return Promise.all(- updates.map((update) => {- const settings = {- type: 'easing' as const,- segmentIndex: update.segmentIndex,- easing,- };-- if (update.type === 'sequence') {- return callUpdateSequenceKeyframeSettings({- fileName: update.fileName,- nodePath: update.nodePath,- fieldKey: update.fieldKey,- settings,- schema: update.schema,- setPropStatuses,- clientId,- });- }-- return callUpdateEffectKeyframeSettings({+ return callBatchUpdateKeyframeSettings({+ sequenceKeyframes: updates+ .filter((update) => update.type === 'sequence')+ .map((update) => ({+ fileName: update.fileName,+ nodePath: update.nodePath,+ fieldKey: update.fieldKey,+ settings: {+ type: 'easing',+ segmentIndex: update.segmentIndex,+ easing,+ },+ schema: update.schema,+ })),+ effectKeyframes: updates+ .filter((update) => update.type === 'effect')+ .map((update) => ({fileName: update.fileName,nodePath: update.nodePath,effectIndex: update.effectIndex,fieldKey: update.fieldKey,- settings,+ settings: {+ type: 'easing',+ segmentIndex: update.segmentIndex,+ easing,+ },schema: update.schema,- setPropStatuses,- clientId,- });- }),- ).then(() => undefined);+ })),+ setPropStatuses,+ clientId,+ });};