🎥 Make videos programmatically with React
`@remotion/studio`: Add keyframe settings modal (#8125)
Jonny Burgerec0d4a202252
diff --git a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.tsindex 8cb21225fd..7016bf94e7 100644--- a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts+++ b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts@@ -20,6 +20,7 @@ import {import type {ExpressionKind, SpreadElementKind} from 'ast-types/lib/gen/kinds';import * as recast from 'recast';import type {+ ExtrapolateType,SequenceFieldSchema,SequenceNodePath,SequenceSchema,@@ -56,6 +57,16 @@ export type KeyframeOperation =type: 'remove';frame: number;}+ | {+ type: 'settings';+ clamping:+ | {+ left: ExtrapolateType;+ right: ExtrapolateType;+ }+ | undefined;+ posterize: number | undefined;+ }| {type: 'move';moves: {@@ -241,6 +252,142 @@ const createClampOptionsExpression = (): ExpressionKind => {]) as ExpressionKind;};+const createEmptyOptionsExpression = (): ObjectExpression =>+ b.objectExpression([]) as ObjectExpression;++const findObjectOptionProperty = (+ options: ObjectExpression,+ propertyName: string,+): {propIndex: number; prop: ObjectProperty | undefined} => {+ const propIndex = options.properties.findIndex(+ (prop) =>+ prop.type === 'ObjectProperty' &&+ !prop.computed &&+ ((prop.key.type === 'Identifier' && prop.key.name === propertyName) ||+ (prop.key.type === 'StringLiteral' && prop.key.value === propertyName)),+ );++ return {+ propIndex,+ prop:+ propIndex === -1+ ? undefined+ : (options.properties[propIndex] as ObjectProperty),+ };+};++const setOptionsProperty = ({+ options,+ propertyName,+ value,+}: {+ options: ObjectExpression;+ propertyName: string;+ value: ExpressionKind | null;+}) => {+ const {propIndex, prop} = findObjectOptionProperty(options, propertyName);+ if (value === null) {+ if (propIndex !== -1) {+ options.properties.splice(propIndex, 1);+ }++ return;+ }++ if (prop) {+ prop.value = value as ObjectProperty['value'];+ return;+ }++ options.properties.push(+ b.objectProperty(b.identifier(propertyName), value) as ObjectProperty,+ );+};++const validatePosterize = (posterize: number | undefined) => {+ if (posterize === undefined) {+ return;+ }++ if (!Number.isFinite(posterize) || posterize <= 0) {+ throw new Error('Cannot update keyframe settings: posterize must be > 0');+ }+};++const updateKeyframeSettings = ({+ expression,+ clamping,+ posterize,+}: {+ expression: Expression;+ clamping:+ | {+ left: ExtrapolateType;+ right: ExtrapolateType;+ }+ | undefined;+ posterize: number | undefined;+}): ExpressionKind => {+ validatePosterize(posterize);++ const existing = getInterpolationExpression(expression);+ if (!existing) {+ throw new Error('Cannot update keyframe settings on non-keyframed value');+ }++ const calleeName =+ existing.callee.type === 'Identifier' ? existing.callee.name : null;+ const isColorInterpolation = calleeName === 'interpolateColors';+ const extraArgs = [...existing.extraArgs];+ const existingOptions = extraArgs[0];+ if (existingOptions && existingOptions.type !== 'ObjectExpression') {+ throw new Error('Cannot update keyframe settings: options must be inline');+ }++ const options =+ existingOptions?.type === 'ObjectExpression'+ ? (existingOptions as ObjectExpression)+ : createEmptyOptionsExpression();++ if (isColorInterpolation) {+ setOptionsProperty({options, propertyName: 'extrapolateLeft', value: null});+ setOptionsProperty({+ options,+ propertyName: 'extrapolateRight',+ value: null,+ });+ } else if (clamping) {+ setOptionsProperty({+ options,+ propertyName: 'extrapolateLeft',+ value: b.stringLiteral(clamping.left),+ });+ setOptionsProperty({+ options,+ propertyName: 'extrapolateRight',+ value: b.stringLiteral(clamping.right),+ });+ }++ setOptionsProperty({+ options,+ propertyName: 'posterize',+ value: posterize === undefined ? null : b.numericLiteral(posterize),+ });++ const nextExtraArgs =+ options.properties.length === 0+ ? extraArgs.slice(1)+ : [options as ExpressionKind, ...extraArgs.slice(1)];++ return createInterpolateExpression({+ callee: existing.callee,+ input: existing.input,+ extraArgs: nextExtraArgs,+ keyframes: existing.keyframes,+ });+};+const createInterpolateExpression = ({callee,input,@@ -494,6 +641,17 @@ const applyKeyframeOperation = ({});}+ if (operation.type === 'settings') {+ return {+ expression: updateKeyframeSettings({+ expression,+ clamping: operation.clamping,+ posterize: operation.posterize,+ }),+ introduced: noIntroducedIdentifiers,+ };+ }+if (operation.type === 'move') {return {expression: moveKeyframes({expression, moves: operation.moves}),diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.tsindex 0fd1486543..309169446e 100644--- a/packages/studio-server/src/preview-server/api-routes.ts+++ b/packages/studio-server/src/preview-server/api-routes.ts@@ -37,6 +37,8 @@ import {unsubscribeFromFileExistence} from './routes/unsubscribe-from-file-existimport {unsubscribeFromSequenceProps} from './routes/unsubscribe-from-sequence-props';import {handleUpdate} from './routes/update-available';import {updateDefaultPropsHandler} from './routes/update-default-props';+import {updateEffectKeyframeSettingsHandler} from './routes/update-effect-keyframe-settings';+import {updateSequenceKeyframeSettingsHandler} from './routes/update-sequence-keyframe-settings';export const allApiRoutes: {[key in keyof ApiRoutes]: ApiHandler<@@ -69,6 +71,9 @@ export const allApiRoutes: {'/api/move-keyframes': moveKeyframesHandler,'/api/add-sequence-keyframe': addSequenceKeyframeHandler,'/api/add-effect-keyframe': addEffectKeyframeHandler,+ '/api/update-sequence-keyframe-settings':+ updateSequenceKeyframeSettingsHandler,+ '/api/update-effect-keyframe-settings': updateEffectKeyframeSettingsHandler,'/api/delete-effect': deleteEffectHandler,'/api/paste-effects': pasteEffectsHandler,'/api/delete-jsx-node': deleteJsxNodeHandler,diff --git a/packages/studio-server/src/preview-server/routes/update-effect-keyframe-settings.ts b/packages/studio-server/src/preview-server/routes/update-effect-keyframe-settings.tsnew file mode 100644index 0000000000..fa2f8a7730--- /dev/null+++ b/packages/studio-server/src/preview-server/routes/update-effect-keyframe-settings.ts@@ -0,0 +1,130 @@+import {readFileSync} from 'node:fs';+import {RenderInternals} from '@remotion/renderer';+import type {+ UpdateEffectKeyframeSettingsRequest,+ UpdateEffectKeyframeSettingsResponse,+} from '@remotion/studio-shared';+import {getAllSchemaKeys} from '@remotion/studio-shared';+import {parseAst} from '../../codemods/parse-ast';+import {updateEffectKeyframes} 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,+ pushToUndoStack,+ suppressUndoStackInvalidation,+} from '../undo-stack';+import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';+import {computeEffectPropStatus} from './can-update-effect-props';+import {findJsxElementAtNodePath} from './can-update-sequence-props';+import {logEffectUpdate} from './log-updates/log-effect-update';+import {withSavePropsLock} from './save-props-mutex';++export const updateEffectKeyframeSettingsHandler: ApiHandler<+ UpdateEffectKeyframeSettingsRequest,+ UpdateEffectKeyframeSettingsResponse+> = ({+ input: {+ fileName,+ sequenceNodePath,+ effectIndex,+ key,+ settings,+ schema,+ clientId,+ },+ remotionRoot,+ logLevel,+}) =>+ withSavePropsLock(async () => {+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[update-effect-keyframe-settings] Received request for fileName="${fileName}" effectIndex=${effectIndex} key="${key}"`,+ );+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName,+ action: 'modify',+ });++ const fileContents = readFileSync(absolutePath, 'utf-8');+ const {+ output,+ oldValueStrings,+ newValueStrings,+ formatted,+ logLine,+ effectCallee,+ updatedSequenceNodePath,+ } = await updateEffectKeyframes({+ input: fileContents,+ sequenceNodePath: sequenceNodePath.nodePath,+ effectIndex,+ schema,+ updates: [+ {+ key,+ operation: {+ type: 'settings',+ clamping: settings.clamping,+ posterize: settings.posterize,+ },+ },+ ],+ });++ const undoPropChange = `${key} keyframe settings reverted`;+ const redoPropChange = `${key} keyframe settings updated`;++ pushToUndoStack({+ filePath: absolutePath,+ oldContents: fileContents,+ newContents: null,+ logLevel,+ remotionRoot,+ logLine,+ description: {+ undoMessage: `↩️ ${undoPropChange}`,+ redoMessage: `↪️ ${redoPropChange}`,+ },+ entryType: 'effect-props',+ suppressHmrOnFileRestore: true,+ });+ suppressUndoStackInvalidation(absolutePath);+ suppressBundlerUpdateForFile(absolutePath);+ writeFileAndNotifyFileWatchers(absolutePath, output, clientId);++ logEffectUpdate({+ fileRelativeToRoot,+ line: logLine,+ effectName: effectCallee,+ propKey: key,+ oldValueString: oldValueStrings[0],+ newValueString: newValueStrings[0],+ defaultValueString: null,+ formatted,+ logLevel,+ removedProps: [],+ addedProps: [],+ });++ printUndoHint(logLevel);++ const ast = parseAst(output);+ const jsx = findJsxElementAtNodePath(ast, updatedSequenceNodePath);+ if (!jsx) {+ return {+ canUpdate: false,+ effectIndex,+ reason: 'not-found',+ };+ }++ return computeEffectPropStatus({+ ast,+ jsx,+ effectIndex,+ keys: getAllSchemaKeys(schema),+ });+ });diff --git a/packages/studio-server/src/preview-server/routes/update-sequence-keyframe-settings.ts b/packages/studio-server/src/preview-server/routes/update-sequence-keyframe-settings.tsnew file mode 100644index 0000000000..891f96c262--- /dev/null+++ b/packages/studio-server/src/preview-server/routes/update-sequence-keyframe-settings.ts@@ -0,0 +1,116 @@+import {readFileSync} from 'node:fs';+import {RenderInternals} from '@remotion/renderer';+import type {+ UpdateSequenceKeyframeSettingsRequest,+ UpdateSequenceKeyframeSettingsResponse,+} from '@remotion/studio-shared';+import {getAllSchemaKeys} from '@remotion/studio-shared';+import {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,+ pushToUndoStack,+ suppressUndoStackInvalidation,+} from '../undo-stack';+import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';+import {computeSequencePropsStatusFromContent} from './can-update-sequence-props';+import {logUpdate} from './log-updates/log-update';+import {withSavePropsLock} from './save-props-mutex';++export const updateSequenceKeyframeSettingsHandler: ApiHandler<+ UpdateSequenceKeyframeSettingsRequest,+ UpdateSequenceKeyframeSettingsResponse+> = ({+ input: {fileName, nodePath, key, settings, schema, clientId},+ remotionRoot,+ logLevel,+}) =>+ withSavePropsLock(async () => {+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[update-sequence-keyframe-settings] Received request for fileName="${fileName}" key="${key}"`,+ );+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName,+ action: 'modify',+ });++ const fileContents = readFileSync(absolutePath, 'utf-8');+ const {+ output,+ oldValueStrings,+ newValueStrings,+ formatted,+ logLine,+ updatedNodePath,+ } = await updateSequenceKeyframes({+ input: fileContents,+ nodePath: nodePath.nodePath,+ schema,+ updates: [+ {+ key,+ operation: {+ type: 'settings',+ clamping: settings.clamping,+ posterize: settings.posterize,+ },+ },+ ],+ });++ const undoPropChange = `${key} keyframe settings reverted`;+ const redoPropChange = `${key} keyframe settings updated`;++ pushToUndoStack({+ filePath: absolutePath,+ oldContents: fileContents,+ newContents: null,+ logLevel,+ remotionRoot,+ logLine,+ description: {+ undoMessage: `↩️ ${undoPropChange}`,+ redoMessage: `↪️ ${redoPropChange}`,+ },+ entryType: 'sequence-props',+ suppressHmrOnFileRestore: true,+ });+ suppressUndoStackInvalidation(absolutePath);+ suppressBundlerUpdateForFile(absolutePath);+ writeFileAndNotifyFileWatchers(absolutePath, output, clientId);++ logUpdate({+ fileRelativeToRoot,+ line: logLine,+ key,+ oldValueString: oldValueStrings[0],+ newValueString: newValueStrings[0],+ defaultValueString: null,+ formatted,+ logLevel,+ removedProps: [],+ addedProps: [],+ });++ printUndoHint(logLevel);++ const status = computeSequencePropsStatusFromContent({+ fileContents: output,+ keys: getAllSchemaKeys(schema),+ nodePath: updatedNodePath,+ effects: [],+ });+ const updatedSubscriptionKey = {...nodePath, nodePath: updatedNodePath};++ return {+ canUpdate: true,+ props: status.props,+ results: [+ {fileName, nodePath: updatedSubscriptionKey, props: status.props},+ ],+ };+ });diff --git a/packages/studio-server/src/test/update-keyframes.test.ts b/packages/studio-server/src/test/update-keyframes.test.tsindex e16fa2de8b..e9d8808e45 100644--- a/packages/studio-server/src/test/update-keyframes.test.ts+++ b/packages/studio-server/src/test/update-keyframes.test.ts@@ -140,6 +140,64 @@ test('updateSequenceKeyframes updates a keyframe at the same frame', async () =>expect(output).toContain('scale: interpolate(frame, [0, 100], [2, 5])');});+test('updateSequenceKeyframes updates keyframe settings while preserving easing', async () => {+ const input = `import React from 'react';+import {AbsoluteFill, Easing, interpolate, useCurrentFrame} from 'remotion';++export const Example: React.FC = () => {+\tconst frame = useCurrentFrame();+\treturn (+\t\t<AbsoluteFill>+\t\t\t<div style={{scale: interpolate(frame, [0, 100], [2, 4], {easing: Easing.linear, extrapolateLeft: 'clamp', posterize: 2})}} />+\t\t</AbsoluteFill>+\t);+};+`;+ const {output} = await updateSequenceKeyframes({+ input,+ nodePath: lineColumnToNodePath(input, getLine(input, 'scale')),+ updates: [+ {+ key: 'style.scale',+ operation: {+ type: 'settings',+ clamping: {left: 'extend', right: 'wrap'},+ posterize: undefined,+ },+ },+ ],+ });++ expect(output).toContain('easing: Easing.linear');+ expect(output).toContain("extrapolateLeft: 'extend'");+ expect(output).toContain("extrapolateRight: 'wrap'");+ expect(output).not.toContain('posterize');+});++test('updateSequenceKeyframes only updates posterize for color keyframes', async () => {+ const {output} = await updateSequenceKeyframes({+ input: colorInput,+ nodePath: lineColumnToNodePath(colorInput, getLine(colorInput, '<Solid')),+ updates: [+ {+ key: 'color',+ operation: {+ type: 'settings',+ clamping: {left: 'extend', right: 'wrap'},+ posterize: 3,+ },+ },+ ],+ });++ expect(output).toContain(+ "color={interpolateColors(frame, [0, 100], ['red', 'blue'], {",+ );+ expect(output).toContain('posterize: 3');+ expect(output).not.toContain('extrapolateLeft');+ expect(output).not.toContain('extrapolateRight');+});+test('updateSequenceKeyframes converts a static value to an interpolation', async () => {const {output, oldValueStrings} = await updateSequenceKeyframes({input: sequenceInput,diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex cecf9bb611..eba0dccd12 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -17,6 +17,7 @@ import type {CanUpdateSequencePropsResponseFalse,CanUpdateSequencePropsResponseTrue,CanUpdateSequencePropStatus,+ ExtrapolateType,SequenceNodePath,SequencePropsSubscriptionKey,SequenceSchema,@@ -442,6 +443,39 @@ export type AddEffectKeyframeRequest = {export type AddEffectKeyframeResponse = SaveEffectPropsResponse;+export type KeyframeSettings = {+ clamping:+ | {+ left: ExtrapolateType;+ right: ExtrapolateType;+ }+ | undefined;+ posterize: number | undefined;+};++export type UpdateSequenceKeyframeSettingsRequest = {+ fileName: string;+ nodePath: SequencePropsSubscriptionKey;+ key: string;+ settings: KeyframeSettings;+ schema: SequenceSchema;+ clientId: string;+};++export type UpdateSequenceKeyframeSettingsResponse = SaveSequencePropsResponse;++export type UpdateEffectKeyframeSettingsRequest = {+ fileName: string;+ sequenceNodePath: SequencePropsSubscriptionKey;+ effectIndex: number;+ key: string;+ settings: KeyframeSettings;+ schema: SequenceSchema;+ clientId: string;+};++export type UpdateEffectKeyframeSettingsResponse = SaveEffectPropsResponse;+type BaseDeleteEffectRequestItem = {fileName: string;sequenceNodePath: SequencePropsSubscriptionKey;@@ -661,6 +695,14 @@ export type ApiRoutes = {AddEffectKeyframeRequest,AddEffectKeyframeResponse>;+ '/api/update-sequence-keyframe-settings': ReqAndRes<+ UpdateSequenceKeyframeSettingsRequest,+ UpdateSequenceKeyframeSettingsResponse+ >;+ '/api/update-effect-keyframe-settings': ReqAndRes<+ UpdateEffectKeyframeSettingsRequest,+ UpdateEffectKeyframeSettingsResponse+ >;'/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 27c10d48a4..2cfa5f2a5e 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -74,10 +74,15 @@ export {UnsubscribeFromDefaultPropsRequest,UnsubscribeFromFileExistenceRequest,UnsubscribeFromSequencePropsRequest,+ UpdateEffectKeyframeSettingsRequest,+ UpdateEffectKeyframeSettingsResponse,UpdateAvailableRequest,UpdateAvailableResponse,UpdateDefaultPropsRequest,UpdateDefaultPropsResponse,+ UpdateSequenceKeyframeSettingsRequest,+ UpdateSequenceKeyframeSettingsResponse,+ type KeyframeSettings,} from './api-requests';export type {ApplyVisualControlCodemod, RecastCodemod} from './codemods';export {DEFAULT_BUFFER_STATE_DELAY_IN_MILLISECONDS} from './default-buffer-state-delay-in-milliseconds';@@ -197,6 +202,10 @@ export {} from './optimistic-move-keyframe';export {optimisticUpdateForCodeValues} from './optimistic-update-for-code-values';export {optimisticUpdateForEffectCodeValues} from './optimistic-update-for-effect-code-values';+export {+ optimisticUpdateEffectKeyframeSettings,+ optimisticUpdateSequenceKeyframeSettings,+} from './optimistic-update-keyframe-settings';export {stringifySequenceExpandedRowKey,stringifySequenceSubscriptionKey,diff --git a/packages/studio-shared/src/optimistic-update-keyframe-settings.ts b/packages/studio-shared/src/optimistic-update-keyframe-settings.tsnew file mode 100644index 0000000000..2ecce6dad0--- /dev/null+++ b/packages/studio-shared/src/optimistic-update-keyframe-settings.ts@@ -0,0 +1,94 @@+import type {+ CanUpdateSequencePropsResponse,+ CanUpdateSequencePropStatus,+} from 'remotion';+import type {KeyframeSettings} from './api-requests';++const applySettingsToStatus = (+ status: CanUpdateSequencePropStatus | undefined,+ settings: KeyframeSettings,+): CanUpdateSequencePropStatus => {+ if (!status || status.status !== 'keyframed') {+ throw new Error('Expected keyframed status');+ }++ return {+ ...status,+ ...(settings.clamping ? {clamping: settings.clamping} : {}),+ posterize: settings.posterize,+ };+};++export const optimisticUpdateSequenceKeyframeSettings = ({+ previous,+ fieldKey,+ settings,+}: {+ previous: CanUpdateSequencePropsResponse;+ fieldKey: string;+ settings: KeyframeSettings;+}): CanUpdateSequencePropsResponse => {+ if (!previous.canUpdate) {+ return previous;+ }++ const status = previous.props[fieldKey];+ if (!status || status.status !== 'keyframed') {+ return previous;+ }++ return {+ ...previous,+ props: {+ ...previous.props,+ [fieldKey]: applySettingsToStatus(status, settings),+ },+ };+};++export const optimisticUpdateEffectKeyframeSettings = ({+ previous,+ effectIndex,+ fieldKey,+ settings,+}: {+ previous: CanUpdateSequencePropsResponse;+ effectIndex: number;+ fieldKey: string;+ settings: KeyframeSettings;+}): CanUpdateSequencePropsResponse => {+ if (!previous.canUpdate) {+ return previous;+ }++ const targetIndex = previous.effects.findIndex(+ (effect) => effect.effectIndex === effectIndex,+ );+ if (targetIndex === -1) {+ return previous;+ }++ const target = previous.effects[targetIndex];+ if (!target.canUpdate) {+ return previous;+ }++ const status = target.props[fieldKey];+ if (!status || status.status !== 'keyframed') {+ return previous;+ }++ const effects = [...previous.effects];+ effects[targetIndex] = {+ ...target,+ props: {+ ...target.props,+ [fieldKey]: applySettingsToStatus(status, settings),+ },+ };++ return {+ ...previous,+ effects,+ };+};diff --git a/packages/studio/src/components/Modals.tsx b/packages/studio/src/components/Modals.tsxindex 32cb7372a3..5723eb2812 100644--- a/packages/studio/src/components/Modals.tsx+++ b/packages/studio/src/components/Modals.tsx@@ -13,6 +13,7 @@ import QuickSwitcher from './QuickSwitcher/QuickSwitcher';import {RenderStatusModal} from './RenderModal/RenderStatusModal';import {RenderModalWithLoader} from './RenderModal/ServerRenderModal';import {WebRenderModalWithLoader} from './RenderModal/WebRenderModal';+import {KeyframeSettingsModal} from './Timeline/KeyframeSettingsModal';import {UpdateModal} from './UpdateModal/UpdateModal';export const Modals: React.FC<{@@ -54,6 +55,9 @@ export const Modals: React.FC<{{modalContextType && modalContextType.type === 'input-props-override' && (<OverrideInputPropsModal />)}+ {modalContextType && modalContextType.type === 'keyframe-settings' && (+ <KeyframeSettingsModal state={modalContextType} />+ )}{modalContextType && modalContextType.type === 'web-render' && (<WebRenderModalWithLoader {...modalContextType} />diff --git a/packages/studio/src/components/Timeline/KeyframeSettingsModal.tsx b/packages/studio/src/components/Timeline/KeyframeSettingsModal.tsxnew file mode 100644index 0000000000..50e040995c--- /dev/null+++ b/packages/studio/src/components/Timeline/KeyframeSettingsModal.tsx@@ -0,0 +1,232 @@+import type {KeyframeSettings} from '@remotion/studio-shared';+import React, {useCallback, useContext, useMemo, useState} from 'react';+import type {+ CanUpdateSequencePropStatusKeyframed,+ ExtrapolateType,+ SequencePropsSubscriptionKey,+ SequenceSchema,+} from 'remotion';+import {Internals} from 'remotion';+import {StudioServerConnectionCtx} from '../../helpers/client-id';+import {INPUT_BACKGROUND} from '../../helpers/colors';+import {ModalsContext} from '../../state/modals';+import {Button} from '../Button';+import {Row, Spacing} from '../layout';+import {ModalButton} from '../ModalButton';+import {ModalFooterContainer} from '../ModalFooter';+import {ModalHeader} from '../ModalHeader';+import {Combobox, type ComboboxValue} from '../NewComposition/ComboBox';+import {DismissableModal} from '../NewComposition/DismissableModal';+import {InputDragger} from '../NewComposition/InputDragger';+import {+ callUpdateEffectKeyframeSettings,+ callUpdateSequenceKeyframeSettings,+} from './call-update-keyframe-settings';++const container: React.CSSProperties = {+ padding: 16,+ width: 520,+};++const row: React.CSSProperties = {+ alignItems: 'center',+ display: 'flex',+ justifyContent: 'space-between',+ marginBottom: 12,+};++const label: React.CSSProperties = {+ fontSize: 13,+};++const helperText: React.CSSProperties = {+ color: 'rgba(255, 255, 255, 0.6)',+ fontSize: 12,+ lineHeight: 1.4,+ marginTop: 4,+};++const comboStyle: React.CSSProperties = {+ minWidth: 150,+};++const posterizeInputStyle: React.CSSProperties = {+ backgroundColor: INPUT_BACKGROUND,+ borderRadius: 4,+ minWidth: 64,+ textAlign: 'right',+};++const extrapolateOptions = [+ 'extend',+ 'clamp',+ 'identity',+ 'wrap',+] as const satisfies ExtrapolateType[];++const labelForExtrapolate = (value: ExtrapolateType) =>+ value[0].toUpperCase() + value.slice(1);++const getExtrapolateValues = (+ onSelect: (value: ExtrapolateType) => void,+): ComboboxValue[] => {+ return extrapolateOptions.map((value) => ({+ type: 'item',+ id: value,+ keyHint: null,+ label: labelForExtrapolate(value),+ leftItem: null,+ disabled: false,+ onClick: () => onSelect(value),+ quickSwitcherLabel: null,+ subMenu: null,+ value,+ }));+};++export type KeyframeSettingsModalState = {+ type: 'keyframe-settings';+ fileName: string;+ nodePath: SequencePropsSubscriptionKey;+ fieldKey: string;+ fieldLabel: string;+ status: CanUpdateSequencePropStatusKeyframed;+ schema: SequenceSchema;+ effectIndex: number | null;+};++export const KeyframeSettingsModal: React.FC<{+ readonly state: KeyframeSettingsModalState;+}> = ({state}) => {+ const {setSelectedModal} = useContext(ModalsContext);+ const {setCodeValues} = useContext(Internals.VisualModeSettersContext);+ const {previewServerState} = useContext(StudioServerConnectionCtx);+ const [left, setLeft] = useState(state.status.clamping.left);+ const [right, setRight] = useState(state.status.clamping.right);+ const [posterize, setPosterize] = useState(state.status.posterize ?? 0);+ const [saving, setSaving] = useState(false);+ const canEditClamping = state.status.interpolationFunction === 'interpolate';++ const close = useCallback(() => {+ setSelectedModal(null);+ }, [setSelectedModal]);++ const leftOptions = useMemo(() => getExtrapolateValues(setLeft), []);+ const rightOptions = useMemo(() => getExtrapolateValues(setRight), []);++ const onPosterizeChange = useCallback((value: number) => {+ setPosterize(Math.max(0, Math.round(value)));+ }, []);++ const posterizeFormatter = useCallback((value: number | string) => {+ const numericValue = Number(value);+ return String(Math.round(numericValue));+ }, []);++ const onSave = useCallback(() => {+ if (previewServerState.type !== 'connected') {+ return;+ }++ const settings: KeyframeSettings = {+ clamping: canEditClamping ? {left, right} : undefined,+ posterize: posterize <= 0 ? undefined : posterize,+ };++ setSaving(true);+ const promise =+ state.effectIndex === null+ ? callUpdateSequenceKeyframeSettings({+ fileName: state.fileName,+ nodePath: state.nodePath,+ fieldKey: state.fieldKey,+ settings,+ schema: state.schema,+ setCodeValues,+ clientId: previewServerState.clientId,+ })+ : callUpdateEffectKeyframeSettings({+ fileName: state.fileName,+ nodePath: state.nodePath,+ effectIndex: state.effectIndex,+ fieldKey: state.fieldKey,+ settings,+ schema: state.schema,+ setCodeValues,+ clientId: previewServerState.clientId,+ });++ promise.then(close).finally(() => {+ setSaving(false);+ });+ }, [+ canEditClamping,+ close,+ left,+ posterize,+ previewServerState,+ right,+ setCodeValues,+ state,+ ]);++ const saveDisabled = saving || previewServerState.type !== 'connected';++ return (+ <DismissableModal>+ <ModalHeader title={`Keyframe settings: ${state.fieldLabel}`} />+ <div style={container}>+ {canEditClamping ? (+ <>+ <div style={row}>+ <div style={label}>Extrapolate left</div>+ <Combobox+ values={leftOptions}+ selectedId={left}+ title="Extrapolate left"+ style={comboStyle}+ />+ </div>+ <div style={row}>+ <div style={label}>Extrapolate right</div>+ <Combobox+ values={rightOptions}+ selectedId={right}+ title="Extrapolate right"+ style={comboStyle}+ />+ </div>+ </>+ ) : null}+ <div style={row}>+ <div>+ <div style={label}>Posterize</div>+ <div style={helperText}>Use 0 to turn posterization off.</div>+ </div>+ <InputDragger+ type="number"+ value={posterize}+ status="ok"+ onValueChange={onPosterizeChange}+ onValueChangeEnd={onPosterizeChange}+ onTextChange={() => undefined}+ min={0}+ step={1}+ formatter={posterizeFormatter}+ rightAlign+ style={posterizeInputStyle}+ />+ </div>+ </div>+ <ModalFooterContainer>+ <Row justify="flex-end" align="center">+ <Button onClick={close}>Cancel</Button>+ <Spacing x={1} />+ <ModalButton onClick={onSave} disabled={saveDisabled}>+ Save+ </ModalButton>+ </Row>+ </ModalFooterContainer>+ </DismissableModal>+ );+};diff --git a/packages/studio/src/components/Timeline/TimelineEffectPropItem.tsx b/packages/studio/src/components/Timeline/TimelineEffectPropItem.tsxindex a006c62b57..f262cec2a1 100644--- a/packages/studio/src/components/Timeline/TimelineEffectPropItem.tsx+++ b/packages/studio/src/components/Timeline/TimelineEffectPropItem.tsx@@ -13,6 +13,7 @@ import type {CodePosition} from '../../error-overlay/react-overlay/utils/get-souimport {StudioServerConnectionCtx} from '../../helpers/client-id';import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';import type {EffectSchemaFieldInfo} from '../../helpers/timeline-layout';+import {ModalsContext} from '../../state/modals';import {callApi} from '../call-api';import {ContextMenu} from '../ContextMenu';import type {ComboboxValue} from '../NewComposition/ComboBox';@@ -340,6 +341,7 @@ export const TimelineEffectPropItem: React.FC<{keyframeDisplayOffset,}) => {const {previewServerState} = useContext(StudioServerConnectionCtx);+ const {setSelectedModal} = useContext(ModalsContext);const {setCodeValues} = useContext(Internals.VisualModeSettersContext);const {codeValues} = useContext(Internals.VisualModeCodeValuesContext);const {getEffectDragOverrides} = useContext(@@ -452,8 +454,34 @@ export const TimelineEffectPropItem: React.FC<{validatedLocation.source,]);+ const onOpenKeyframeSettings = useCallback(() => {+ if (propStatus === null || !isKeyframedStatus(propStatus)) {+ return;+ }++ setSelectedModal({+ type: 'keyframe-settings',+ fileName: validatedLocation.source,+ nodePath,+ fieldKey: field.key,+ fieldLabel: field.description ?? field.key,+ status: propStatus,+ schema: field.effectSchema,+ effectIndex: field.effectIndex,+ });+ }, [+ field.description,+ field.effectIndex,+ field.effectSchema,+ field.key,+ nodePath,+ propStatus,+ setSelectedModal,+ validatedLocation.source,+ ]);+const contextMenuValues = useMemo((): ComboboxValue[] => {- return [+ const values: ComboboxValue[] = [{type: 'item',id: 'reset-effect-field',@@ -467,7 +495,30 @@ export const TimelineEffectPropItem: React.FC<{value: 'reset-effect-field',},];- }, [canShowReset, onReset]);++ if (propStatus !== null && isKeyframedStatus(propStatus)) {+ values.push({+ type: 'item',+ id: 'keyframe-settings-effect-field',+ keyHint: null,+ label: 'Keyframe settings...',+ leftItem: null,+ disabled: previewServerState.type !== 'connected',+ onClick: onOpenKeyframeSettings,+ quickSwitcherLabel: null,+ subMenu: null,+ value: 'keyframe-settings-effect-field',+ });+ }++ return values;+ }, [+ canShowReset,+ onOpenKeyframeSettings,+ onReset,+ previewServerState,+ propStatus,+ ]);const row = (<TimelineRowChromediff --git a/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx b/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsxindex 5fe7660614..0a953fa406 100644--- a/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx+++ b/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx@@ -16,6 +16,7 @@ import type {TimelineFieldOnDragValueChange,TimelineFieldOnSave,} from '../../helpers/timeline-layout';+import {ModalsContext} from '../../state/modals';import {ContextMenu} from '../ContextMenu';import type {ComboboxValue} from '../NewComposition/ComboBox';import {callAddSequenceKeyframe} from './call-add-keyframe';@@ -210,6 +211,7 @@ export const TimelineSequencePropItem: React.FC<{Internals.VisualModeSettersContext,);const {previewServerState} = useContext(StudioServerConnectionCtx);+ const {setSelectedModal} = useContext(ModalsContext);const selection = useTimelineRowSelection(nodePathInfo);const clientId =previewServerState.type === 'connected'@@ -365,8 +367,33 @@ export const TimelineSequencePropItem: React.FC<{clearDragOverrides(nodePath);}, [clearDragOverrides, nodePath]);+ const onOpenKeyframeSettings = useCallback(() => {+ if (codeValue === null || !isKeyframedStatus(codeValue)) {+ return;+ }++ setSelectedModal({+ type: 'keyframe-settings',+ fileName: validatedLocation.source,+ nodePath,+ fieldKey: field.key,+ fieldLabel: field.description ?? field.key,+ status: codeValue,+ schema,+ effectIndex: null,+ });+ }, [+ codeValue,+ field.description,+ field.key,+ nodePath,+ schema,+ setSelectedModal,+ validatedLocation.source,+ ]);+const contextMenuValues = useMemo((): ComboboxValue[] => {- return [+ const values: ComboboxValue[] = [{type: 'item',id: 'reset-sequence-field',@@ -380,7 +407,30 @@ export const TimelineSequencePropItem: React.FC<{value: 'reset-sequence-field',},];- }, [canShowReset, onReset]);++ if (codeValue !== null && isKeyframedStatus(codeValue)) {+ values.push({+ type: 'item',+ id: 'keyframe-settings-sequence-field',+ keyHint: null,+ label: 'Keyframe settings...',+ leftItem: null,+ disabled: previewServerState.type !== 'connected',+ onClick: onOpenKeyframeSettings,+ quickSwitcherLabel: null,+ subMenu: null,+ value: 'keyframe-settings-sequence-field',+ });+ }++ return values;+ }, [+ canShowReset,+ codeValue,+ onOpenKeyframeSettings,+ onReset,+ previewServerState,+ ]);if (codeValue === null) {return null;diff --git a/packages/studio/src/components/Timeline/call-update-keyframe-settings.ts b/packages/studio/src/components/Timeline/call-update-keyframe-settings.tsnew file mode 100644index 0000000000..aec7009ccd--- /dev/null+++ b/packages/studio/src/components/Timeline/call-update-keyframe-settings.ts@@ -0,0 +1,91 @@+import {+ optimisticUpdateEffectKeyframeSettings,+ optimisticUpdateSequenceKeyframeSettings,+ type KeyframeSettings,+} from '@remotion/studio-shared';+import type {SequencePropsSubscriptionKey, SequenceSchema} from 'remotion';+import {callApi} from '../call-api';+import {enqueueSavePropChange} from './save-prop-queue';+import type {SetCodeValues} from './save-sequence-prop';++export const callUpdateSequenceKeyframeSettings = ({+ fileName,+ nodePath,+ fieldKey,+ settings,+ schema,+ setCodeValues,+ clientId,+}: {+ fileName: string;+ nodePath: SequencePropsSubscriptionKey;+ fieldKey: string;+ settings: KeyframeSettings;+ schema: SequenceSchema;+ setCodeValues: SetCodeValues;+ clientId: string;+}): Promise<void> => {+ return enqueueSavePropChange({+ nodePath,+ setCodeValues,+ applyOptimistic: (prev) =>+ optimisticUpdateSequenceKeyframeSettings({+ previous: prev,+ fieldKey,+ settings,+ }),+ apiCall: () =>+ callApi('/api/update-sequence-keyframe-settings', {+ fileName,+ nodePath,+ key: fieldKey,+ settings,+ schema,+ clientId,+ }),+ errorLabel: 'Could not update keyframe settings',+ });+};++export const callUpdateEffectKeyframeSettings = ({+ fileName,+ nodePath,+ effectIndex,+ fieldKey,+ settings,+ schema,+ setCodeValues,+ clientId,+}: {+ fileName: string;+ nodePath: SequencePropsSubscriptionKey;+ effectIndex: number;+ fieldKey: string;+ settings: KeyframeSettings;+ schema: SequenceSchema;+ setCodeValues: SetCodeValues;+ clientId: string;+}): Promise<void> => {+ return enqueueSavePropChange({+ nodePath,+ setCodeValues,+ applyOptimistic: (prev) =>+ optimisticUpdateEffectKeyframeSettings({+ previous: prev,+ effectIndex,+ fieldKey,+ settings,+ }),+ apiCall: () =>+ callApi('/api/update-effect-keyframe-settings', {+ fileName,+ sequenceNodePath: nodePath,+ effectIndex,+ key: fieldKey,+ settings,+ schema,+ clientId,+ }),+ errorLabel: 'Could not update keyframe settings',+ });+};diff --git a/packages/studio/src/state/modals.ts b/packages/studio/src/state/modals.tsindex f4521f206b..d3b69142d4 100644--- a/packages/studio/src/state/modals.ts+++ b/packages/studio/src/state/modals.ts@@ -26,6 +26,7 @@ import type {_InternalTypes} from 'remotion';import type {CompType} from '../components/NewComposition/DuplicateComposition';import type {QuickSwitcherMode} from '../components/QuickSwitcher/NoResults';import type {RenderType} from '../components/RenderModal/RenderModalAdvanced';+import type {KeyframeSettingsModalState} from '../components/Timeline/KeyframeSettingsModal';import type {Bug, UpdateInfo} from '../components/UpdateCheck';export type WebRenderModalState = {@@ -137,6 +138,7 @@ export type ModalState =| {type: 'input-props-override';}+ | KeyframeSettingsModalState| RenderModalState| WebRenderModalState| {