🎥 Make videos programmatically with React
`@remotion/browser-studio`: Add, duplicate, reorder, edit, paste, and delete effects (#10642)
Jonny Burgerc4256eaf1e2b
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.tsindex fa25f42d14..78b1b708a2 100644--- a/packages/browser-studio/src/browser-studio-operations.ts+++ b/packages/browser-studio/src/browser-studio-operations.ts@@ -1,7 +1,10 @@import {+ addEffect as addEffectCodemod,computeSequencePropsStatusFromContent,computeSequencePropsSubscriptionFromContent,deleteJsxNodes,+ deleteEffects as deleteEffectsCodemod,+ duplicateEffects as duplicateEffectsCodemod,duplicateCompositionInSource,findProjectFile,getCanUpdateDefaultPropsForProject,@@ -15,12 +18,15 @@ import {JsxElementNotFoundAtLocationError,makeInMemoryInsertJsxElementCodemodEnvironment,parseAndApplyCodemod,+ pasteEffects as pasteEffectsCodemod,+ reorderEffect as reorderEffectCodemod,reorderSequence as reorderSequenceCodemod,resolveCompositionComponentWithFile,simpleDiff,splitJsxSequence as splitJsxSequenceCodemod,splitVideoFromAudio as splitVideoFromAudioCodemod,updateDefaultProps as updateDefaultPropsCodemod,+ updateEffectProps as updateEffectPropsCodemod,updateEffectKeyframes,updateSequenceKeyframes,type EffectKeyframeUpdate,@@ -33,7 +39,9 @@ import {} from '@remotion/studio-protocol';import {getAllSchemaKeys,+ getRequiredPackageForEffectImportPath,getRequiredPackageForInsertableElement,+ type BrowserStudioEffectOperations,type BrowserStudioKeyframeOperations,type BrowserStudioOperations,type ElementInstallExpectedFileState,@@ -97,6 +105,12 @@ const formatInline: FormatInline = ({inlineContent, linePrefix, endOfLine}) =>}),});+const getStructuredError = (error: unknown) => ({+ success: false as const,+ reason: error instanceof Error ? error.message : String(error),+ stack: error instanceof Error && error.stack ? error.stack : '',+});+export {insertSolidIntoProject,insertSolidIntoProjectWithNodePathRemappings,@@ -758,6 +772,402 @@ export const createBrowserStudioOperations = ({return resolved;};+ const getEffectStatus = ({+ effectIndex,+ fileName,+ project,+ schema,+ sequenceNodePath,+ }: {+ effectIndex: number;+ fileName: string;+ project: VirtualProject;+ schema: InteractivitySchema;+ sequenceNodePath: SequencePropsSubscriptionKey;+ }) => {+ const absolutePath = findProjectFile({filePath: fileName, project});+ const status = computeSequencePropsStatusFromContent({+ fileContents: project.files[absolutePath],+ nodePath: sequenceNodePath.nodePath,+ componentIdentity: null,+ keys: [],+ effects: Array.from({length: effectIndex + 1}, (_, index) =>+ index === effectIndex ? getAllSchemaKeys(schema) : [],+ ),+ videoConfigValues: sequenceNodePath.videoConfigValues,+ });+ return (+ status.effects[effectIndex] ?? {+ canUpdate: false as const,+ effectIndex,+ reason: 'not-found' as const,+ }+ );+ };++ const effectOperations: BrowserStudioEffectOperations = {+ addEffect: async (request) => {+ try {+ const requiredPackage = getRequiredPackageForEffectImportPath(+ request.effectImportPath,+ );+ const dependencies =+ requiredPackage === null+ ? {}+ : await resolveElementDependencies([+ {name: requiredPackage, version: null},+ ]);+ const project = addDependenciesToProject({+ dependencies,+ project: getProject(),+ });+ const absolutePath = findProjectFile({+ filePath: request.fileName,+ project,+ });+ const result = await addEffectCodemod({+ effectConfig: request.effectConfig,+ effectImportPath: request.effectImportPath,+ effectName: request.effectName,+ formatFile: formatCodemodFile,+ input: project.files[absolutePath],+ sequenceNodePath: request.sequenceNodePath.nodePath,+ });+ controller.applyMutation({+ fileName: absolutePath,+ nodePathMutationFiles: null,+ mutate: () => ({+ ...project,+ files: {...project.files, [absolutePath]: result.output},+ }),+ });+ return {success: true};+ } catch (error) {+ return getStructuredError(error);+ }+ },+ deleteEffects: async (request) => {+ try {+ if (request.length === 0) {+ throw new Error('No effects were specified for deletion');+ }++ const project = getProject();+ const groups = new Map<+ string,+ Array<+ | {+ type: 'single-effect';+ effectIndex: number;+ sequenceNodePath: SequenceNodePath;+ }+ | {type: 'all-effects'; sequenceNodePath: SequenceNodePath}+ >+ >();+ for (const item of request) {+ const absolutePath = findProjectFile({+ filePath: item.fileName,+ project,+ });+ const group = groups.get(absolutePath) ?? [];+ group.push(+ item.type === 'single-effect'+ ? {+ type: 'single-effect',+ effectIndex: item.effectIndex,+ sequenceNodePath: item.sequenceNodePath.nodePath,+ }+ : {+ type: 'all-effects',+ sequenceNodePath: item.sequenceNodePath.nodePath,+ },+ );+ groups.set(absolutePath, group);+ }++ const updates = await Promise.all(+ [...groups].map(async ([absolutePath, targets]) => ({+ absolutePath,+ result: await deleteEffectsCodemod({+ effects: targets,+ formatFile: formatCodemodFile,+ input: project.files[absolutePath],+ }),+ })),+ );+ controller.applyMutation({+ fileName: updates.map((update) => update.absolutePath).join(', '),+ nodePathMutationFiles: null,+ mutate: () => ({+ ...project,+ files: {+ ...project.files,+ ...Object.fromEntries(+ updates.map((update) => [+ update.absolutePath,+ update.result.output,+ ]),+ ),+ },+ }),+ });+ return {success: true};+ } catch (error) {+ return getStructuredError(error);+ }+ },+ duplicateEffects: async (request) => {+ try {+ if (request.length === 0) {+ throw new Error('No effects were specified for duplication');+ }++ const project = getProject();+ const groups = new Map<+ string,+ Array<{+ effectIndex: number;+ sequenceNodePath: SequenceNodePath;+ }>+ >();+ for (const item of request) {+ const absolutePath = findProjectFile({+ filePath: item.fileName,+ project,+ });+ const group = groups.get(absolutePath) ?? [];+ group.push({+ effectIndex: item.effectIndex,+ sequenceNodePath: item.sequenceNodePath.nodePath,+ });+ groups.set(absolutePath, group);+ }++ const updates = await Promise.all(+ [...groups].map(async ([absolutePath, targets]) => ({+ absolutePath,+ result: await duplicateEffectsCodemod({+ effects: targets,+ formatFile: formatCodemodFile,+ input: project.files[absolutePath],+ }),+ })),+ );+ controller.applyMutation({+ fileName: updates.map((update) => update.absolutePath).join(', '),+ nodePathMutationFiles: null,+ mutate: () => ({+ ...project,+ files: {+ ...project.files,+ ...Object.fromEntries(+ updates.map((update) => [+ update.absolutePath,+ update.result.output,+ ]),+ ),+ },+ }),+ });+ return {success: true};+ } catch (error) {+ return getStructuredError(error);+ }+ },+ pasteEffects: async (request) => {+ try {+ const packageNames = new Set(+ request.effects.flatMap((effect) => {+ const packageName = getRequiredPackageForEffectImportPath(+ effect.importPath,+ );+ return packageName === null ? [] : [packageName];+ }),+ );+ const dependencies = await resolveElementDependencies(+ [...packageNames].map((name) => ({name, version: null})),+ );+ const project = addDependenciesToProject({+ dependencies,+ project: getProject(),+ });+ const absolutePath = findProjectFile({+ filePath: request.targetFileName,+ project,+ });+ const result = await pasteEffectsCodemod({+ effects: request.effects,+ formatFile: formatCodemodFile,+ input: project.files[absolutePath],+ insertAtIndices: request.insertAtIndices,+ targetSequenceNodePath: request.targetSequenceNodePath.nodePath,+ type: request.type,+ });+ controller.applyMutation({+ fileName: absolutePath,+ nodePathMutationFiles: null,+ mutate: () => ({+ ...project,+ files: {...project.files, [absolutePath]: result.output},+ }),+ });+ return {success: true};+ } catch (error) {+ return getStructuredError(error);+ }+ },+ reorderEffect: async (request) => {+ try {+ const project = getProject();+ const absolutePath = findProjectFile({+ filePath: request.fileName,+ project,+ });+ const result = await reorderEffectCodemod({+ formatFile: formatCodemodFile,+ fromIndex: request.fromIndex,+ input: project.files[absolutePath],+ sequenceNodePath: request.sequenceNodePath.nodePath,+ toIndex: request.toIndex,+ });+ controller.applyMutation({+ fileName: absolutePath,+ nodePathMutationFiles: null,+ mutate: () => ({+ ...project,+ files: {...project.files, [absolutePath]: result.output},+ }),+ });+ return {success: true};+ } catch (error) {+ return getStructuredError(error);+ }+ },+ saveEffectProps: async (request) => {+ const project = getProject();+ const absolutePath = findProjectFile({+ filePath: request.fileName,+ project,+ });+ const result = await updateEffectPropsCodemod({+ effectIndex: request.effectIndex,+ formatFile: formatCodemodFile,+ input: project.files[absolutePath],+ schema: request.schema,+ sequenceNodePath: request.sequenceNodePath.nodePath,+ update:+ request.type === 'effect-param'+ ? {+ defaultValue:+ request.defaultValue === null+ ? null+ : JSON.parse(request.defaultValue),+ effectParam: request.effectParam,+ key: request.key,+ }+ : {+ defaultValue:+ request.defaultValue === null+ ? null+ : JSON.parse(request.defaultValue),+ key: request.key,+ value: JSON.parse(request.value),+ },+ });+ const nextProject = {+ ...project,+ files: {...project.files, [absolutePath]: result.output},+ };+ controller.applyMutation({+ fileName: absolutePath,+ nodePathMutationFiles: null,+ mutate: () => nextProject,+ });+ return getEffectStatus({+ effectIndex: request.effectIndex,+ fileName: request.fileName,+ project: nextProject,+ schema: request.schema,+ sequenceNodePath: request.sequenceNodePath,+ });+ },+ saveMultipleEffectProps: async (request) => {+ if (request.edits.length === 0) {+ throw new Error('No effect prop edits to save');+ }++ const project = getProject();+ const outputByPath = new Map<string, string>();+ for (const edit of request.edits) {+ const absolutePath = findProjectFile({+ filePath: edit.fileName,+ project,+ });+ const result = await updateEffectPropsCodemod({+ effectIndex: edit.effectIndex,+ formatFile: formatCodemodFile,+ input: outputByPath.get(absolutePath) ?? project.files[absolutePath],+ schema: edit.schema,+ sequenceNodePath: edit.sequenceNodePath.nodePath,+ update:+ edit.type === 'effect-param'+ ? {+ defaultValue:+ edit.defaultValue === null+ ? null+ : JSON.parse(edit.defaultValue),+ effectParam: edit.effectParam,+ key: edit.key,+ }+ : {+ defaultValue:+ edit.defaultValue === null+ ? null+ : JSON.parse(edit.defaultValue),+ key: edit.key,+ value: JSON.parse(edit.value),+ },+ });+ outputByPath.set(absolutePath, result.output);+ }++ const nextProject = {+ ...project,+ files: {...project.files, ...Object.fromEntries(outputByPath)},+ };+ controller.applyMutation({+ fileName: request.undoLabel,+ nodePathMutationFiles: null,+ mutate: () => nextProject,+ });+ const targets = [+ ...new Map(+ request.edits.map((edit) => [+ JSON.stringify([+ edit.fileName,+ edit.sequenceNodePath.nodePath,+ edit.effectIndex,+ ]),+ edit,+ ]),+ ).values(),+ ];+ return {+ results: targets.map((edit) => ({+ fileName: edit.fileName,+ sequenceNodePath: edit.sequenceNodePath,+ status: getEffectStatus({+ effectIndex: edit.effectIndex,+ fileName: edit.fileName,+ project: nextProject,+ schema: edit.schema,+ sequenceNodePath: edit.sequenceNodePath,+ }),+ })),+ };+ },+ };+const deleteJsxNode: BrowserStudioOperations['deleteJsxNode'] = async ({nodes,}) => {@@ -1442,6 +1852,7 @@ export const createBrowserStudioOperations = ({}),),duplicateComposition,+ effects: effectOperations,emitEvent: controller.emitEvent,findInFile: controller.findInFile,getFileSource: controller.getFileSource,diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.tsindex a0616ff5d6..0dba4cced3 100644--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts@@ -1583,3 +1583,225 @@ test('reports structured failures for unsupported codemods', async () => {expect(getProject().files).toEqual(initialFiles);});++test('mutates effects in the virtual project and reports structured failures', async () => {+ const fileName = '/project/src/Comp.tsx';+ const initialContents = `import {brightness} from '@remotion/effects/brightness';+import {contrast} from '@remotion/effects/contrast';+import {AbsoluteFill} from 'remotion';++export const Comp = () => (+ <AbsoluteFill effects={[brightness({amount: 1}), contrast({amount: 2})]} />+);+`;+ let currentProject: VirtualProject = {+ rootDir: '/project',+ entryPoint: fileName,+ files: {+ [fileName]: initialContents,+ '/project/package.json': '{"dependencies": {}}',+ },+ };+ let projectChanges = 0;+ const operations = createBrowserStudioOperations({+ dependencyVersions: {remotion: '4.0.514'},+ getStaticFiles: null,+ getProject: () => currentProject,+ initialElement: null,+ onProjectChange: (project) => {+ projectChanges++;+ currentProject = project;+ },+ resolveDependencies: null,+ });+ const subscription = await operations.subscribeToSequenceProps({+ fileName: 'src/Comp.tsx',+ line: 6,+ column: 2,+ nodePath: null,+ componentIdentity: null,+ keys: [],+ assetKeys: [],+ effects: [['amount'], ['amount']],+ clientId: 'browser-studio',+ videoConfigValues: {+ durationInFrames: 60,+ fps: 30,+ height: 720,+ width: 1280,+ },+ });+ if (!subscription.success || !operations.effects) {+ throw new Error('Expected Browser Studio effect capability');+ }++ const {effects} = operations;+ const addResult = await effects.addEffect({+ fileName: 'src/Comp.tsx',+ sequenceNodePath: subscription.nodePath,+ effectName: 'tint',+ effectImportPath: '@remotion/effects/tint',+ effectConfig: {color: 'red'},+ clientId: 'browser-studio',+ });+ expect(addResult).toEqual({success: true});+ expect(currentProject.files[fileName]).toContain('tint({');+ expect(currentProject.files['/project/package.json']).toContain(+ '"@remotion/effects": "4.0.514"',+ );++ expect(+ await effects.duplicateEffects([+ {+ fileName: 'src/Comp.tsx',+ sequenceNodePath: subscription.nodePath,+ effectIndex: 0,+ },+ ]),+ ).toEqual({success: true});+ expect(currentProject.files[fileName].match(/brightness\(\{/g)).toHaveLength(+ 2,+ );++ expect(+ await effects.reorderEffect({+ fileName: 'src/Comp.tsx',+ sequenceNodePath: subscription.nodePath,+ fromIndex: 3,+ toIndex: 0,+ clientId: 'browser-studio',+ }),+ ).toEqual({success: true});+ expect(currentProject.files[fileName].indexOf('tint({')).toBeLessThan(+ currentProject.files[fileName].indexOf('brightness({'),+ );++ const effectSchema = {+ amount: {type: 'number', default: 1, hiddenFromList: false},+ } satisfies InteractivitySchema;+ const editResult = await effects.saveEffectProps({+ type: 'value',+ fileName: 'src/Comp.tsx',+ sequenceNodePath: subscription.nodePath,+ effectIndex: 1,+ key: 'amount',+ value: '0.5',+ defaultValue: '1',+ schema: effectSchema,+ clientId: 'browser-studio',+ });+ expect(editResult).toMatchObject({+ canUpdate: true,+ effectIndex: 1,+ props: {amount: {status: 'static', codeValue: 0.5}},+ });+ expect(currentProject.files[fileName]).toContain('amount: 0.5');++ const multipleEditResult = await effects.saveMultipleEffectProps({+ edits: [+ {+ type: 'value',+ fileName: 'src/Comp.tsx',+ sequenceNodePath: subscription.nodePath,+ effectIndex: 2,+ key: 'amount',+ value: '0.25',+ defaultValue: '1',+ schema: effectSchema,+ },+ ],+ clientId: 'browser-studio',+ undoLabel: 'Undo effect edits',+ redoLabel: 'Redo effect edits',+ });+ expect(multipleEditResult.results[0]?.status).toMatchObject({+ canUpdate: true,+ props: {amount: {status: 'static', codeValue: 0.25}},+ });++ expect(+ await effects.pasteEffects({+ targetFileName: 'src/Comp.tsx',+ targetSequenceNodePath: subscription.nodePath,+ type: 'effects-additive',+ effects: [+ {+ callee: 'blur',+ importPath: '@remotion/effects/blur',+ params: {radius: {type: 'static', value: 12}},+ },+ ],+ clientId: 'browser-studio',+ insertAtIndices: null,+ }),+ ).toEqual({success: true});+ expect(currentProject.files[fileName]).toContain('blur({');++ const beforeDelete = currentProject.files[fileName];+ expect(+ await effects.deleteEffects([+ {+ type: 'single-effect',+ fileName: 'src/Comp.tsx',+ sequenceNodePath: subscription.nodePath,+ effectIndex: 0,+ },+ ]),+ ).toEqual({success: true});+ expect(currentProject.files[fileName].indexOf('tint({')).toBe(-1);+ expect(await operations.undo()).toMatchObject({success: true});+ expect(currentProject.files[fileName]).toBe(beforeDelete);+ expect(await operations.redo()).toMatchObject({success: true});+ expect(currentProject.files[fileName].indexOf('tint({')).toBe(-1);+ expect(projectChanges).toBeGreaterThanOrEqual(9);++ const beforeFailures = currentProject.files[fileName];+ expect(+ await effects.duplicateEffects([+ {+ fileName: 'src/Comp.tsx',+ sequenceNodePath: subscription.nodePath,+ effectIndex: 99,+ },+ ]),+ ).toEqual({+ success: false,+ reason: 'Cannot duplicate effect: not-found',+ stack: expect.any(String),+ });+ expect(+ await effects.addEffect({+ fileName: 'src/Comp.tsx',+ sequenceNodePath: subscription.nodePath,+ effectName: 'unsafe',+ effectImportPath: 'untrusted-package',+ effectConfig: {},+ clientId: 'browser-studio',+ }),+ ).toEqual({+ success: false,+ reason: 'Unsupported effect import "untrusted-package"',+ stack: expect.any(String),+ });+ expect(+ await effects.pasteEffects({+ targetFileName: 'src/Comp.tsx',+ targetSequenceNodePath: subscription.nodePath,+ type: 'effects-additive',+ effects: [+ {+ callee: 'blur',+ importPath: '@remotion/effects/blur',+ params: {},+ },+ ],+ clientId: 'browser-studio',+ insertAtIndices: [0, 1],+ }),+ ).toEqual({+ success: false,+ reason: 'Cannot paste effects: invalid insertion indices',+ stack: expect.any(String),+ });+ expect(currentProject.files[fileName]).toBe(beforeFailures);+});diff --git a/packages/studio-codemods/src/effect-operations.ts b/packages/studio-codemods/src/effect-operations.tsnew file mode 100644index 0000000000..37feb77b8d--- /dev/null+++ b/packages/studio-codemods/src/effect-operations.ts@@ -0,0 +1,694 @@+import type {+ ArrayExpression,+ CallExpression,+ Expression,+ File,+ JSXAttribute,+ JSXOpeningElement,+ ObjectExpression,+ ObjectProperty,+ StringLiteral,+} from '@babel/types';+import type {+ EffectClipboardParam,+ EffectClipboardPasteType,+ EffectClipboardSnapshot,+} from '@remotion/studio-shared';+import type {ExpressionKind} from 'ast-types/lib/gen/kinds';+import * as recast from 'recast';+import type {InteractivitySchema, SequenceNodePath} from 'remotion';+import {NoReactInternals} from 'remotion/no-react';+import {+ ensureUseCurrentFrameHook,+ findEnclosingFunctionPath,+} from './ensure-imports-and-frame-hook';+import {findJsxElementAtNodePath} from './sequence-props';+import {+ findEffectCallExpression,+ findEffectsAttr,+} from './sequence-props/can-update-effect-props';+import {+ ensureClipboardParamRemotionImports,+ getRequiredRemotionImportsForClipboardParams,+ makeClipboardParamExpression,+ type ClipboardParamRemotionLocalNames,+} from './sequence-props/clipboard-param-expression';+import {enumerateEffectArrayElements} from './sequence-props/effect-array-elements';+import {getAstNodePath} from './sequence-props/get-ast-node-path';+import {ensureNamedImport} from './sequence-props/imports';+import {parseAst, serializeAst} from './sequence-props/parse-ast';+import {parseValueExpression} from './update-nested-prop';++const b = recast.types.builders;+const identifierRegex = /^[A-Za-z_$][0-9A-Za-z_$]*$/;++/*+ * Deep-clones an AST subtree while sharing `loc` objects by reference, like+ * Babel's `cloneNode`. A runtime import of `@babel/types` is avoided because+ * it reads `process.env` at module load, which breaks browser bundles.+ */+const cloneAstValue = <T>(value: T): T => {+ if (Array.isArray(value)) {+ return value.map((item) => cloneAstValue(item)) as T;+ }++ if (value !== null && typeof value === 'object') {+ const clone: Record<string, unknown> = {};+ for (const [key, item] of Object.entries(value)) {+ clone[key] = key === 'loc' ? item : cloneAstValue(item);+ }++ return clone as T;+ }++ return value;+};++export type FormatEffectFile = (input: {contents: string}) => Promise<{+ formatted: boolean;+ output: string;+}>;++export type EffectTarget = {+ sequenceNodePath: SequenceNodePath;+ effectIndex: number;+};++export type EffectDeletionTarget = {+ sequenceNodePath: SequenceNodePath;+} & ({type: 'single-effect'; effectIndex: number} | {type: 'all-effects'});++export type EffectPropUpdate =+ | {key: string; value: unknown; defaultValue: unknown | null}+ | {+ key: string;+ effectParam: EffectClipboardParam;+ defaultValue: unknown | null;+ };++const formatAst = (ast: File, formatFile: FormatEffectFile) =>+ formatFile({contents: serializeAst(ast)});++const getEffectsArray = (attr: JSXAttribute, action: string) => {+ if (!attr.value || attr.value.type !== 'JSXExpressionContainer') {+ throw new Error(`Cannot ${action} effect: effects prop is not an array`);+ }++ const expression = attr.value.expression as Expression;+ if (expression.type !== 'ArrayExpression') {+ throw new Error(`Cannot ${action} effect: effects prop is not an array`);+ }++ return expression;+};++const makeEffectsAttr = (array: ArrayExpression): JSXAttribute =>+ b.jsxAttribute(+ b.jsxIdentifier('effects'),+ b.jsxExpressionContainer(array as never),+ ) as unknown as JSXAttribute;++const getJsx = ({+ action,+ ast,+ sequenceNodePath,+}: {+ action: string;+ ast: File;+ sequenceNodePath: SequenceNodePath;+}) => {+ const jsx = findJsxElementAtNodePath(ast, sequenceNodePath);+ if (!jsx) {+ throw new Error(+ `Could not find a JSX element at the specified location to ${action} effect`,+ );+ }++ return jsx;+};++const assertValidEffect = ({+ effectImportPath,+ effectName,+}: {+ effectImportPath: string;+ effectName: string;+}) => {+ if (!identifierRegex.test(effectName)) {+ throw new Error(`Invalid effect name "${effectName}"`);+ }++ if (+ !effectImportPath.startsWith('@remotion/effects/') &&+ effectImportPath !== '@remotion/light-leaks' &&+ effectImportPath !== '@remotion/starburst'+ ) {+ throw new Error(`Unsupported effect import "${effectImportPath}"`);+ }+};++const hasTopLevelBinding = (ast: File, name: string) =>+ ast.program.body.some((node) => {+ const declaration =+ node.type === 'ExportNamedDeclaration' ? node.declaration : node;+ if (+ declaration?.type === 'ClassDeclaration' ||+ declaration?.type === 'FunctionDeclaration'+ ) {+ return declaration.id?.name === name;+ }++ if (declaration?.type === 'VariableDeclaration') {+ return declaration.declarations.some(+ (item) => item.id.type === 'Identifier' && item.id.name === name,+ );+ }++ return (+ node.type === 'ImportDeclaration' &&+ node.specifiers?.some((specifier) => specifier.local?.name === name)+ );+ });++const ensureEffectImport = ({+ ast,+ effectImportPath,+ effectName,+}: {+ ast: File;+ effectImportPath: string;+ effectName: string;+}) => {+ assertValidEffect({effectImportPath, effectName});+ let localName = effectName;+ if (hasTopLevelBinding(ast, localName)) {+ localName = `${effectName}Effect`;+ let suffix = 2;+ while (hasTopLevelBinding(ast, localName)) {+ localName = `${effectName}Effect${suffix++}`;+ }+ }++ return ensureNamedImport({+ ast,+ importedName: effectName,+ localName,+ sourcePath: effectImportPath,+ });+};++const makeConfigObject = (config: Record<string, unknown>) =>+ b.objectExpression(+ Object.entries(config).map(([key, value]) =>+ b.objectProperty(+ identifierRegex.test(key) ? b.identifier(key) : b.stringLiteral(key),+ parseValueExpression(value),+ ),+ ) as never,+ ) as ObjectExpression;++export const addEffect = async ({+ effectConfig,+ effectImportPath,+ effectName,+ formatFile,+ input,+ sequenceNodePath,+}: {+ effectConfig: Record<string, unknown>;+ effectImportPath: string;+ effectName: string;+ formatFile: FormatEffectFile;+ input: string;+ sequenceNodePath: SequenceNodePath;+}) => {+ const ast = parseAst(input);+ const jsx = getJsx({action: 'add', ast, sequenceNodePath});+ const localName = ensureEffectImport({ast, effectImportPath, effectName});+ const effectCall = b.callExpression(b.identifier(localName), [+ makeConfigObject(effectConfig) as never,+ ]);+ const attr = findEffectsAttr(jsx.attributes);+ if (attr) {+ getEffectsArray(attr, 'add').elements.push(effectCall as never);+ } else {+ jsx.attributes.push(+ makeEffectsAttr(+ b.arrayExpression([effectCall as never]) as ArrayExpression,+ ),+ );+ }++ const formatted = await formatAst(ast, formatFile);+ return formatted;+};++export const duplicateEffects = async ({+ effects,+ formatFile,+ input,+}: {+ effects: EffectTarget[];+ formatFile: FormatEffectFile;+ input: string;+}) => {+ if (effects.length === 0) {+ throw new Error('No effects were specified for duplication');+ }++ const ast = parseAst(input);+ const effectsByAttribute = new Map<+ JSXAttribute,+ {array: ArrayExpression; indices: Set<number>}+ >();+ for (const {effectIndex, sequenceNodePath} of effects) {+ const jsx = getJsx({action: 'duplicate', ast, sequenceNodePath});+ const attr = findEffectsAttr(jsx.attributes);+ if (!attr) {+ throw new Error('Could not find effects on the target JSX element');+ }++ const found = findEffectCallExpression({attr, effectIndex});+ if (found.kind === 'error') {+ throw new Error(`Cannot duplicate effect: ${found.reason}`);+ }++ const group = effectsByAttribute.get(attr) ?? {+ array: getEffectsArray(attr, 'duplicate'),+ indices: new Set<number>(),+ };+ group.indices.add(effectIndex);+ effectsByAttribute.set(attr, group);+ }++ for (const {array, indices} of effectsByAttribute.values()) {+ for (const effectIndex of [...indices].sort((a, bValue) => bValue - a)) {+ const effect = array.elements[effectIndex];+ if (!effect || effect.type !== 'CallExpression') {+ throw new Error('Cannot duplicate effect: not-call-expression');+ }++ array.elements.splice(effectIndex + 1, 0, cloneAstValue(effect) as never);+ }+ }++ const formatted = await formatAst(ast, formatFile);+ return formatted;+};++export const reorderEffect = async ({+ formatFile,+ fromIndex,+ input,+ sequenceNodePath,+ toIndex,+}: {+ formatFile: FormatEffectFile;+ fromIndex: number;+ input: string;+ sequenceNodePath: SequenceNodePath;+ toIndex: number;+}) => {+ const ast = parseAst(input);+ const jsx = getJsx({action: 'reorder', ast, sequenceNodePath});+ const attr = findEffectsAttr(jsx.attributes);+ if (!attr) {+ throw new Error('Could not find effects on the target JSX element');+ }++ const array = getEffectsArray(attr, 'reorder');+ const elements = enumerateEffectArrayElements(array);+ if (fromIndex < 0 || fromIndex >= elements.length) {+ throw new Error('Cannot reorder effect: source index not-found');+ }++ if (toIndex < 0 || toIndex >= elements.length) {+ throw new Error('Cannot reorder effect: target index not-found');+ }++ if (elements[fromIndex].kind !== 'call') {+ throw new Error(+ 'Cannot reorder effect: source effect is not-call-expression',+ );+ }++ if (fromIndex !== toIndex) {+ const [moved] = array.elements.splice(fromIndex, 1);+ array.elements.splice(toIndex, 0, moved as never);+ }++ const formatted = await formatAst(ast, formatFile);+ return formatted;+};++export const deleteEffects = async ({+ effects,+ formatFile,+ input,+}: {+ effects: EffectDeletionTarget[];+ formatFile: FormatEffectFile;+ input: string;+}) => {+ if (effects.length === 0) {+ throw new Error('No effects were specified for deletion');+ }++ const ast = parseAst(input);+ const effectsByAttribute = new Map<+ JSXAttribute,+ {+ all: boolean;+ array: ArrayExpression;+ attributes: JSXOpeningElement['attributes'];+ indices: Set<number>;+ }+ >();+ for (const effect of effects) {+ const jsx = getJsx({+ action: 'delete',+ ast,+ sequenceNodePath: effect.sequenceNodePath,+ });+ const attr = findEffectsAttr(jsx.attributes);+ if (!attr) {+ throw new Error('Could not find effects on the target JSX element');+ }++ const group = effectsByAttribute.get(attr) ?? {+ all: false,+ array: getEffectsArray(attr, 'delete'),+ attributes: jsx.attributes,+ indices: new Set<number>(),+ };+ effectsByAttribute.set(attr, group);+ if (effect.type === 'all-effects') {+ if (group.array.elements.length === 0) {+ throw new Error('Cannot delete effect: no effects found');+ }++ group.all = true;+ group.indices.clear();+ continue;+ }++ if (!group.all && !group.indices.has(effect.effectIndex)) {+ const found = findEffectCallExpression({+ attr,+ effectIndex: effect.effectIndex,+ });+ if (found.kind === 'error') {+ throw new Error(`Cannot delete effect: ${found.reason}`);+ }++ group.indices.add(effect.effectIndex);+ }+ }++ for (const [attr, group] of effectsByAttribute) {+ if (!group.all) {+ for (const index of [...group.indices].sort((a, bValue) => bValue - a)) {+ group.array.elements.splice(index, 1);+ }+ }++ if (group.all || group.array.elements.length === 0) {+ const index = group.attributes.indexOf(attr);+ if (index !== -1) {+ group.attributes.splice(index, 1);+ }+ }+ }++ const formatted = await formatAst(ast, formatFile);+ return formatted;+};++const makeEffectCall = ({+ ast,+ effect,+ localNames,+}: {+ ast: File;+ effect: EffectClipboardSnapshot;+ localNames: ClipboardParamRemotionLocalNames;+}) => {+ const effectName = ensureEffectImport({+ ast,+ effectImportPath: effect.importPath,+ effectName: effect.callee,+ });+ const properties = Object.entries(effect.params).map(([key, param]) =>+ b.objectProperty(+ identifierRegex.test(key) ? b.identifier(key) : b.stringLiteral(key),+ makeClipboardParamExpression({param, localNames}),+ ),+ ) as ObjectProperty[];+ return b.callExpression(b.identifier(effectName), [+ b.objectExpression(properties as never),+ ]) as CallExpression;+};++const ensureFrameHook = ({+ ast,+ localNames,+ sequenceNodePath,+}: {+ ast: File;+ localNames: ClipboardParamRemotionLocalNames;+ sequenceNodePath: SequenceNodePath;+}) => {+ const jsxPath = getAstNodePath(ast, sequenceNodePath);+ if (!jsxPath) {+ return;+ }++ const functionPath = findEnclosingFunctionPath(jsxPath);+ if (functionPath) {+ ensureUseCurrentFrameHook(+ functionPath,+ localNames.useCurrentFrame ?? 'useCurrentFrame',+ );+ }+};++export const pasteEffects = async ({+ effects,+ formatFile,+ input,+ insertAtIndices,+ targetSequenceNodePath,+ type,+}: {+ effects: EffectClipboardSnapshot[];+ formatFile: FormatEffectFile;+ input: string;+ insertAtIndices: number[] | null;+ targetSequenceNodePath: SequenceNodePath;+ type: EffectClipboardPasteType;+}) => {+ const ast = parseAst(input);+ const jsx = getJsx({+ action: 'paste',+ ast,+ sequenceNodePath: targetSequenceNodePath,+ });+ const requiredImports = getRequiredRemotionImportsForClipboardParams(+ effects.flatMap((effect) => Object.values(effect.params)),+ );+ const localNames = ensureClipboardParamRemotionImports({+ ast,+ requiredImports,+ });+ if (requiredImports.has('useCurrentFrame')) {+ ensureFrameHook({+ ast,+ localNames,+ sequenceNodePath: targetSequenceNodePath,+ });+ }++ const calls = effects.map((effect) =>+ makeEffectCall({ast, effect, localNames}),+ );+ const existingAttr = findEffectsAttr(jsx.attributes);+ if (+ insertAtIndices !== null &&+ (type !== 'effects-additive' ||+ insertAtIndices.length !== calls.length ||+ new Set(insertAtIndices).size !== insertAtIndices.length ||+ insertAtIndices.some((index) => !Number.isInteger(index) || index < 0))+ ) {+ throw new Error('Cannot paste effects: invalid insertion indices');+ }++ if (type === 'effects-replacing') {+ if (existingAttr) {+ jsx.attributes.splice(jsx.attributes.indexOf(existingAttr), 1);+ }++ if (calls.length > 0) {+ jsx.attributes.push(+ makeEffectsAttr(b.arrayExpression(calls as never) as ArrayExpression),+ );+ }+ } else if (calls.length === 0) {+ throw new Error('Cannot paste effects: no effects were copied');+ } else if (insertAtIndices === null) {+ if (existingAttr) {+ getEffectsArray(existingAttr, 'paste').elements.push(+ ...(calls as ArrayExpression['elements']),+ );+ } else {+ jsx.attributes.push(+ makeEffectsAttr(b.arrayExpression(calls as never) as ArrayExpression),+ );+ }+ } else {+ const elements = existingAttr+ ? getEffectsArray(existingAttr, 'paste').elements+ : ([] as ArrayExpression['elements']);+ for (const item of calls+ .map((effect, index) => ({effect, index: insertAtIndices[index]!}))+ .sort((a, bValue) => a.index - bValue.index)) {+ elements.splice(Math.min(item.index, elements.length), 0, item.effect);+ }++ if (!existingAttr) {+ jsx.attributes.push(+ makeEffectsAttr(+ b.arrayExpression(elements as never) as ArrayExpression,+ ),+ );+ }+ }++ const formatted = await formatAst(ast, formatFile);+ return formatted;+};++const isEffectParamUpdate = (+ update: EffectPropUpdate,+): update is Extract<EffectPropUpdate, {effectParam: EffectClipboardParam}> =>+ 'effectParam' in update;++const findObjectProperty = (object: ObjectExpression, key: string) =>+ object.properties.find(+ (property): property is ObjectProperty =>+ property.type === 'ObjectProperty' &&+ ((property.key.type === 'Identifier' && property.key.name === key) ||+ (property.key.type === 'StringLiteral' &&+ (property.key as StringLiteral).value === key)),+ );++const makeEffectPropExpression = ({+ ast,+ sequenceNodePath,+ update,+}: {+ ast: File;+ sequenceNodePath: SequenceNodePath;+ update: EffectPropUpdate;+}): ExpressionKind => {+ if (!isEffectParamUpdate(update)) {+ return parseValueExpression(update.value);+ }++ const requiredImports = getRequiredRemotionImportsForClipboardParams([+ update.effectParam,+ ]);+ const localNames = ensureClipboardParamRemotionImports({+ ast,+ requiredImports,+ });+ if (requiredImports.has('useCurrentFrame')) {+ ensureFrameHook({ast, localNames, sequenceNodePath});+ }++ return makeClipboardParamExpression({param: update.effectParam, localNames});+};++export const updateEffectProps = async ({+ effectIndex,+ formatFile,+ input,+ schema,+ sequenceNodePath,+ update,+}: {+ effectIndex: number;+ formatFile: FormatEffectFile;+ input: string;+ schema: InteractivitySchema;+ sequenceNodePath: SequenceNodePath;+ update: EffectPropUpdate;+}) => {+ const ast = parseAst(input);+ const jsx = getJsx({action: 'update', ast, sequenceNodePath});+ const attr = findEffectsAttr(jsx.attributes);+ if (!attr) {+ throw new Error('Could not find effects on the target JSX element');+ }++ const found = findEffectCallExpression({attr, effectIndex});+ if (found.kind === 'error') {+ throw new Error(`Cannot update effect prop: ${found.reason}`);+ }++ const isDefault =+ !isEffectParamUpdate(update) &&+ update.defaultValue !== null &&+ JSON.stringify(update.value) === JSON.stringify(update.defaultValue);+ let object: ObjectExpression;+ if (found.call.arguments.length === 0) {+ if (isDefault) {+ const unchangedFormatted = await formatAst(ast, formatFile);+ return unchangedFormatted;+ }++ object = b.objectExpression([]) as ObjectExpression;+ found.call.arguments.push(object);+ } else if (found.call.arguments[0].type !== 'ObjectExpression') {+ throw new Error('Cannot update effect prop: computed');+ } else {+ object = found.call.arguments[0] as ObjectExpression;+ }++ const existing = findObjectProperty(object, update.key);+ if (isDefault) {+ if (existing) {+ object.properties.splice(object.properties.indexOf(existing), 1);+ }+ } else {+ const value = makeEffectPropExpression({ast, sequenceNodePath, update});+ if (existing) {+ existing.value = value as ObjectProperty['value'];+ } else {+ object.properties.push(+ b.objectProperty(b.identifier(update.key), value) as ObjectProperty,+ );+ }+ }++ const staticValue = isEffectParamUpdate(update)+ ? update.effectParam.type === 'static'+ ? update.effectParam.value+ : null+ : update.value;+ const field = schema[update.key];+ if (field?.type === 'enum' && staticValue !== null) {+ for (const key of NoReactInternals.findPropsToDelete({+ key: update.key,+ schema,+ value: staticValue,+ })) {+ const property = findObjectProperty(object, key);+ if (property) {+ object.properties.splice(object.properties.indexOf(property), 1);+ }+ }+ }++ const formatted = await formatAst(ast, formatFile);+ return formatted;+};diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.tsindex 5c23c62d69..e49b338568 100644--- a/packages/studio-codemods/src/index.ts+++ b/packages/studio-codemods/src/index.ts@@ -20,6 +20,18 @@ export {getJsxElementTagLabel,} from './delete-jsx-node';export {duplicateCompositionInSource} from './duplicate-composition';+export {+ addEffect,+ deleteEffects,+ duplicateEffects,+ pasteEffects,+ reorderEffect,+ updateEffectProps,+ type EffectDeletionTarget,+ type EffectPropUpdate,+ type EffectTarget,+ type FormatEffectFile,+} from './effect-operations';export {ensureRemotionImports,ensureUseCurrentFrameHook,diff --git a/packages/studio-shared/src/browser-studio-operations.ts b/packages/studio-shared/src/browser-studio-operations.tsindex 036d5c96ee..6f799368a6 100644--- a/packages/studio-shared/src/browser-studio-operations.ts+++ b/packages/studio-shared/src/browser-studio-operations.ts@@ -2,6 +2,8 @@ import type {ElementDragData} from '@remotion/studio-protocol';import type {AddEffectKeyframeRequest,AddEffectKeyframeResponse,+ AddEffectRequest,+ AddEffectResponse,AddKeyframesRequest,AddKeyframesResponse,AddSequenceKeyframeRequest,@@ -16,25 +18,37 @@ import type {DeleteJsxNodeResponse,DeleteKeyframesRequest,DeleteKeyframesResponse,+ DeleteEffectRequest,+ DeleteEffectResponse,DeleteStaticFileRequest,DeleteStaticFileResponse,FindInFileRequest,FindInFileResponse,+ DuplicateEffectRequest,+ DuplicateEffectResponse,InsertJsxElementRequest,InsertJsxElementResponse,InsertElementRequest,InsertElementResponse,MoveKeyframesRequest,MoveKeyframesResponse,+ PasteEffectsRequest,+ PasteEffectsResponse,PrepareElementInstallRequest,PrepareElementInstallResponse,RedoResponse,RenameStaticFileRequest,RenameStaticFileResponse,+ ReorderEffectRequest,+ ReorderEffectResponse,ReorderSequenceRequest,ReorderSequenceResponse,SaveSequencePropsRequest,SaveSequencePropsResponse,+ SaveEffectPropsRequest,+ SaveEffectPropsResponse,+ SaveMultipleEffectPropsRequest,+ SaveMultipleEffectPropsResponse,SimpleDiff,SplitJsxSequenceRequest,SplitJsxSequenceResponse,@@ -103,6 +117,26 @@ export type BrowserStudioKeyframeOperations = {) => Promise<UpdateSequenceKeyframeSettingsResponse>;};+export type BrowserStudioEffectOperations = {+ addEffect: (request: AddEffectRequest) => Promise<AddEffectResponse>;+ deleteEffects: (+ request: DeleteEffectRequest,+ ) => Promise<DeleteEffectResponse>;+ duplicateEffects: (+ request: DuplicateEffectRequest,+ ) => Promise<DuplicateEffectResponse>;+ pasteEffects: (request: PasteEffectsRequest) => Promise<PasteEffectsResponse>;+ reorderEffect: (+ request: ReorderEffectRequest,+ ) => Promise<ReorderEffectResponse>;+ saveEffectProps: (+ request: SaveEffectPropsRequest,+ ) => Promise<SaveEffectPropsResponse>;+ saveMultipleEffectProps: (+ request: SaveMultipleEffectPropsRequest,+ ) => Promise<SaveMultipleEffectPropsResponse>;+};+export type BrowserStudioOperations = {consumeInitialElement: () => {element: ElementDragData['element'];@@ -122,6 +156,8 @@ export type BrowserStudioOperations = {duplicateComposition: (request: DuplicateCompositionRequest,) => Promise<DuplicateCompositionResponse>;+ /** Optional for compatibility with older Browser Studio hosts. */+ effects?: BrowserStudioEffectOperations;findInFile: (request: FindInFileRequest) => Promise<FindInFileResponse>;getFileSource: (fileName: string) => Promise<string | null>;getCompositionFile: (compositionId: string) => string | null;diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex 4d85f85645..fb4882d171 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -157,6 +157,7 @@ export {} from './api-requests';export type {BrowserStudioKeyframeOperations,+ BrowserStudioEffectOperations,BrowserStudioOperations,DuplicateCompositionRequest,DuplicateCompositionResponse,diff --git a/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx b/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsxindex eb3370fb76..a5a8fc1a91 100644--- a/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx+++ b/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx@@ -24,6 +24,7 @@ import {type InteractivitySchema,type TSequence,} from 'remotion';+import {canUseEffectOperations} from '../../helpers/browser-studio-operations';import {StudioServerConnectionCtx} from '../../helpers/client-id';import {hasClipboardFigmaPayload} from '../../helpers/clipboard-figma';import {hasClipboardImage} from '../../helpers/clipboard-images';@@ -33,8 +34,8 @@ import {areKeyboardShortcutsDisabled,useKeybinding,} from '../../helpers/use-keybinding';-import {callApi} from '../call-api';import {useConfirmationDialog} from '../ConfirmationDialog';+import {pasteEffects} from '../effect-operations-api';import {showNotification} from '../Notifications/NotificationCenter';import {callAddKeyframes} from './call-add-keyframe';import {callDeleteKeyframes} from './call-delete-keyframe';@@ -1367,6 +1368,10 @@ export const TimelineClipboardKeybindings: React.FC = () => {return;}+ if (!canUseEffectOperations()) {+ return;+ }+e.preventDefault();if (result.status === 'unsupported-version') {@@ -1403,7 +1408,7 @@ export const TimelineClipboardKeybindings: React.FC = () => {envelope?.sourceIdentity === makeTargetKey(targetSequenceNodePath)? envelope.originalEffectIndices: null;- return callApi('/api/paste-effects', {+ return pasteEffects({targetFileName: targetSequenceNodePath.absolutePath,targetSequenceNodePath,type: payload.type,diff --git a/packages/studio/src/components/Timeline/TimelineEffectItem.tsx b/packages/studio/src/components/Timeline/TimelineEffectItem.tsxindex 76f0d4f8a8..25c4a4d604 100644--- a/packages/studio/src/components/Timeline/TimelineEffectItem.tsx+++ b/packages/studio/src/components/Timeline/TimelineEffectItem.tsx@@ -2,6 +2,7 @@ import React, {useCallback, useContext, useMemo, useState} from 'react';import type {SequencePropsSubscriptionKey, InteractivitySchema} from 'remotion';import {Internals} from 'remotion';import type {CodePosition} from '../../error-overlay/react-overlay/utils/get-source-map';+import {canUseEffectOperations} from '../../helpers/browser-studio-operations';import {StudioServerConnectionCtx} from '../../helpers/client-id';import {TIMELINE_BLUE, WHITE_ALPHA_80} from '../../helpers/colors';import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';@@ -9,8 +10,8 @@ import {EXPANDED_SECTION_PADDING_RIGHT,TREE_GROUP_ROW_HEIGHT,} from '../../helpers/timeline-layout';-import {callApi} from '../call-api';import {ContextMenu} from '../ContextMenu';+import {deleteEffects, reorderEffect} from '../effect-operations-api';import type {GetIsExpanded} from '../ExpandedTracksProvider';import type {ComboboxValue} from '../NewComposition/ComboBox';import {showNotification} from '../Notifications/NotificationCenter';@@ -138,6 +139,7 @@ export const TimelineEffectItem: React.FC<{}) => {const {previewServerState} = useContext(StudioServerConnectionCtx);const previewConnected = previewServerState.type === 'connected';+ const canMutateEffects = canUseEffectOperations();const {propStatuses} = useContext(Internals.VisualModePropStatusesContext);const {setPropStatuses} = useContext(Internals.VisualModeSettersContext);const selection = useTimelineRowSelection(nodePathInfo);@@ -169,15 +171,18 @@ export const TimelineEffectItem: React.FC<{return false;}, [disabledStatus]);- const canToggle = previewConnected && disabledStatus?.status === 'static';+ const canToggle =+ previewConnected && canMutateEffects && disabledStatus?.status === 'static';const deleteDisabled =!previewConnected ||+ !canMutateEffects ||effectStatus.type !== 'can-update-effect' ||!validatedLocation.source;const canReorder =previewConnected &&+ canMutateEffects &&effectStatus.type === 'can-update-effect' &&Boolean(validatedLocation.source);@@ -192,7 +197,7 @@ export const TimelineEffectItem: React.FC<{}try {- const result = await callApi('/api/delete-effect', [+ const result = await deleteEffects([{type: 'single-effect',fileName: validatedLocation.source,@@ -429,7 +434,7 @@ export const TimelineEffectItem: React.FC<{currentEffectDrag = null;try {- const result = await callApi('/api/reorder-effect', {+ const result = await reorderEffect({fileName: validatedLocation.source,sequenceNodePath: nodePath,fromIndex: dropTarget.dragData.effectIndex,diff --git a/packages/studio/src/components/Timeline/TimelineEffectPropItem.tsx b/packages/studio/src/components/Timeline/TimelineEffectPropItem.tsxindex 6341e802c5..3fe9e86738 100644--- a/packages/studio/src/components/Timeline/TimelineEffectPropItem.tsx+++ b/packages/studio/src/components/Timeline/TimelineEffectPropItem.tsx@@ -13,13 +13,14 @@ import type {} from 'remotion';import {Internals} from 'remotion';import type {CodePosition} from '../../error-overlay/react-overlay/utils/get-source-map';+import {canUseEffectOperations} from '../../helpers/browser-studio-operations';import {StudioServerConnectionCtx} from '../../helpers/client-id';import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';import {openOriginalPositionInEditorAtProperty} from '../../helpers/open-in-editor';import type {EffectSchemaFieldInfo} from '../../helpers/timeline-layout';import {useRuntimeStoreValue} from '../../helpers/use-runtime-values';-import {callApi} from '../call-api';import {ContextMenu} from '../ContextMenu';+import {saveEffectProps} from '../effect-operations-api';import type {ComboboxValue} from '../NewComposition/ComboBox';import {useEditorOpening} from '../use-default-editor-info';import {callAddEffectKeyframe} from './call-add-keyframe';@@ -219,7 +220,7 @@ export const TimelineEffectPropValue: React.FC<{schema: field.effectSchema,}),apiCall: () =>- callApi('/api/save-effect-props', {+ saveEffectProps({type: 'value',fileName: validatedLocation.source,sequenceNodePath: nodePath,@@ -283,6 +284,10 @@ export const TimelineEffectPropValue: React.FC<{throw new Error(`Effects do not support scale fields: ${field.key}`);}+ if (!canUseEffectOperations()) {+ return <UnsupportedStatus label="read only" formattedValue={false} />;+ }+if (effectStatus.type === 'cannot-update-effect') {if (effectStatus.reason === 'computed') {return (diff --git a/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx b/packages/studio/src/components/Timeline/TimelineSequenceItem.tsxindex 9a0975c599..0f0003d4eb 100644--- a/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx+++ b/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx@@ -7,6 +7,7 @@ import type {} from 'remotion';import {Internals} from 'remotion';import {areSequenceNodePathInfosEqual} from '../../helpers/are-sequence-node-path-infos-equal';+import {canUseEffectOperations} from '../../helpers/browser-studio-operations';import {StudioServerConnectionCtx} from '../../helpers/client-id';import {BORDER_TIMELINE_DROP_BLUE,@@ -19,7 +20,10 @@ import {getSequenceDoubleClickAction,} from '../../helpers/get-sequence-double-click-action';import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';-import {isStudioInteractivityEnabled} from '../../helpers/interactivity-enabled';+import {+ isStudioInteractivityEnabled,+ isStudioSelectionEnabled,+} from '../../helpers/interactivity-enabled';import {getStudioKeyboardShortcutsEnabled} from '../../helpers/studio-runtime-config';import {getTimelineLayerHeight,@@ -287,6 +291,8 @@ const TimelineSequenceItemInner: React.FC<{const {previewServerState} = useContext(StudioServerConnectionCtx);const previewConnected = previewServerState.type === 'connected';const previewInteractive = previewConnected && isStudioInteractivityEnabled();+ const canMutateEffects =+ previewConnected && isStudioSelectionEnabled() && canUseEffectOperations();const {getIsExpanded} = useContext(ExpandedTracksGetterContext);const {setPropStatuses} = useContext(Internals.VisualModeSettersContext);const {setSelectedModal} = useContext(SetSelectedModalContext);@@ -876,7 +882,7 @@ const TimelineSequenceItemInner: React.FC<{const canAddEffect =nodePathInfo?.supportsEffects === true &&- previewInteractive &&+ canMutateEffects &&Boolean(validatedLocation?.source);const canCrop = useRuntimeValueSelector({controls: sequence.controls,@@ -1133,7 +1139,7 @@ const TimelineSequenceItemInner: React.FC<{validatedLocation?.source,]);const canDropEffect =- previewInteractive &&+ canMutateEffects &&nodePath !== null &&validatedLocation !== null &&sequence.controls?.supportsEffects === true;diff --git a/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts b/packages/studio/src/components/Timeline/delete-selected-timeline-item.tsindex a5560081b0..61e76e1490 100644--- a/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts+++ b/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts@@ -1,9 +1,10 @@import type {OverrideIdToNodePaths, PropStatuses, TSequence} from 'remotion';import {Internals} from 'remotion';+import {canUseEffectOperations} from '../../helpers/browser-studio-operations';import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';-import {callApi} from '../call-api';import type {ConfirmationDialogFunction} from '../ConfirmationDialog-types';import {deleteJsxNode} from '../delete-jsx-node-api';+import {deleteEffects as deleteEffectsApi} from '../effect-operations-api';import {showNotification} from '../Notifications/NotificationCenter';import {deleteSelectedKeyframes} from './delete-selected-keyframe';import {findTrackForNodePathInfo} from './find-track-for-node-path-info';@@ -97,8 +98,11 @@ const deleteEffects = (return Promise.resolve(false);}- return callApi(- '/api/delete-effect',+ if (!canUseEffectOperations()) {+ return Promise.resolve(false);+ }++ return deleteEffectsApi(effects.map((effect) => {const nodePath = effect.nodePathInfo.sequenceSubscriptionKey;return effect.type === 'single-effect'diff --git a/packages/studio/src/components/Timeline/duplicate-selected-timeline-item.ts b/packages/studio/src/components/Timeline/duplicate-selected-timeline-item.tsindex 6a17be4590..9686db19d8 100644--- a/packages/studio/src/components/Timeline/duplicate-selected-timeline-item.ts+++ b/packages/studio/src/components/Timeline/duplicate-selected-timeline-item.ts@@ -1,6 +1,8 @@+import {canUseEffectOperations} from '../../helpers/browser-studio-operations';import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';import {callApi} from '../call-api';import type {ConfirmationDialogFunction} from '../ConfirmationDialog-types';+import {duplicateEffects} from '../effect-operations-api';import {showNotification} from '../Notifications/NotificationCenter';import type {TimelineSelection} from './TimelineSelection';@@ -101,8 +103,7 @@ export const isDuplicatableEffectSelection = (const duplicateEffectsFromSource = (effects: readonly (TimelineSelection & {type: 'sequence-effect'})[],): Promise<void> => {- return callApi(- '/api/duplicate-effect',+ return duplicateEffects(effects.map((effect) => {const nodePath = effect.nodePathInfo.sequenceSubscriptionKey;@@ -148,7 +149,7 @@ export const duplicateSelectedTimelineItems = ({}const effectSelections = selections.filter(isDuplicatableEffectSelection);- if (effectSelections.length === 0) {+ if (effectSelections.length === 0 || !canUseEffectOperations()) {return null;}diff --git a/packages/studio/src/components/Timeline/save-effect-prop.ts b/packages/studio/src/components/Timeline/save-effect-prop.tsindex 84e4e6de41..809dfed37c 100644--- a/packages/studio/src/components/Timeline/save-effect-prop.ts+++ b/packages/studio/src/components/Timeline/save-effect-prop.ts@@ -4,7 +4,10 @@ import {type SaveMultipleEffectPropsEdit,} from '@remotion/studio-shared';import type {SequencePropsSubscriptionKey, InteractivitySchema} from 'remotion';-import {callApi} from '../call-api';+import {+ saveEffectProps as saveEffectPropsApi,+ saveMultipleEffectProps as saveMultipleEffectPropsApi,+} from '../effect-operations-api';import {applyEffectResponseToPropStatuses} from './apply-effect-response-to-prop-statuses';import {enqueueSavePropChange} from './save-prop-queue';import type {SetPropStatuses} from './save-sequence-prop';@@ -73,7 +76,7 @@ export const saveMultipleEffectProps = ({);}- return callApi('/api/save-multiple-effect-props', {+ return saveMultipleEffectPropsApi({edits: changes.map((change): SaveMultipleEffectPropsEdit =>change.type === 'effect-param'@@ -141,8 +144,7 @@ export const saveEffectProp = (input: SaveEffectPropInput): Promise<void> => {applyServerResponse: (prev, response) =>applyEffectResponseToPropStatuses({previous: prev, response}),apiCall: () =>- callApi(- '/api/save-effect-props',+ saveEffectPropsApi(input.type === 'effect-param'? {type: 'effect-param',diff --git a/packages/studio/src/components/effect-drag-and-drop.ts b/packages/studio/src/components/effect-drag-and-drop.tsindex 3712efcbc1..3bfe614902 100644--- a/packages/studio/src/components/effect-drag-and-drop.ts+++ b/packages/studio/src/components/effect-drag-and-drop.ts@@ -4,8 +4,9 @@ import {} from '@remotion/studio-protocol';import {getRequiredPackageForEffectImportPath} from '@remotion/studio-shared';import type {SequencePropsSubscriptionKey} from 'remotion';+import {getBrowserStudioEffectOperations} from '../helpers/browser-studio-operations';import {installRequiredPackages} from '../helpers/install-required-package';-import {callApi} from './call-api';+import {addEffect} from './effect-operations-api';import {showNotification} from './Notifications/NotificationCenter';export const hasEffectDragType = (dataTransfer: DataTransfer) => {@@ -60,11 +61,13 @@ export const addEffectToSequence = async ({const requiredPackage = getRequiredPackageForEffectImportPath(effect.importPath,);- await installRequiredPackages(- requiredPackage ? [{name: requiredPackage, version: null}] : [],- );+ if (getBrowserStudioEffectOperations() === null) {+ await installRequiredPackages(+ requiredPackage ? [{name: requiredPackage, version: null}] : [],+ );+ }- const result = await callApi('/api/add-effect', {+ const result = await addEffect({fileName,sequenceNodePath: nodePath,effectName: effect.name,diff --git a/packages/studio/src/components/effect-operations-api.ts b/packages/studio/src/components/effect-operations-api.tsnew file mode 100644index 0000000000..bd825c0289--- /dev/null+++ b/packages/studio/src/components/effect-operations-api.ts@@ -0,0 +1,50 @@+import type {+ AddEffectRequest,+ DeleteEffectRequest,+ DuplicateEffectRequest,+ PasteEffectsRequest,+ ReorderEffectRequest,+ SaveEffectPropsRequest,+ SaveMultipleEffectPropsRequest,+} from '@remotion/studio-shared';+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';+import {callApi} from './call-api';++const getBrowserEffectOperations = () => {+ const browserStudio = getBrowserStudioOperations();+ if (browserStudio !== null && browserStudio.effects === undefined) {+ throw new Error('Effect editing is not supported by this Browser Studio');+ }++ return browserStudio?.effects ?? null;+};++export const addEffect = (request: AddEffectRequest) =>+ getBrowserEffectOperations()?.addEffect(request) ??+ callApi('/api/add-effect', request);++export const deleteEffects = (request: DeleteEffectRequest) =>+ getBrowserEffectOperations()?.deleteEffects(request) ??+ callApi('/api/delete-effect', request);++export const duplicateEffects = (request: DuplicateEffectRequest) =>+ getBrowserEffectOperations()?.duplicateEffects(request) ??+ callApi('/api/duplicate-effect', request);++export const pasteEffects = (request: PasteEffectsRequest) =>+ getBrowserEffectOperations()?.pasteEffects(request) ??+ callApi('/api/paste-effects', request);++export const reorderEffect = (request: ReorderEffectRequest) =>+ getBrowserEffectOperations()?.reorderEffect(request) ??+ callApi('/api/reorder-effect', request);++export const saveEffectProps = (request: SaveEffectPropsRequest) =>+ getBrowserEffectOperations()?.saveEffectProps(request) ??+ callApi('/api/save-effect-props', request);++export const saveMultipleEffectProps = (+ request: SaveMultipleEffectPropsRequest,+) =>+ getBrowserEffectOperations()?.saveMultipleEffectProps(request) ??+ callApi('/api/save-multiple-effect-props', request);diff --git a/packages/studio/src/helpers/browser-studio-operations.ts b/packages/studio/src/helpers/browser-studio-operations.tsindex bf2415b236..0df8533b60 100644--- a/packages/studio/src/helpers/browser-studio-operations.ts+++ b/packages/studio/src/helpers/browser-studio-operations.ts@@ -17,6 +17,13 @@ export const getBrowserStudioOperations =export const getBrowserStudioKeyframeOperations = () =>getBrowserStudioOperations()?.keyframes ?? null;+export const getBrowserStudioEffectOperations = () =>+ getBrowserStudioOperations()?.effects ?? null;+export const canUseKeyframeOperations = () =>!window.remotion_isReadOnlyStudio ||getBrowserStudioKeyframeOperations() !== null;++export const canUseEffectOperations = () =>+ !window.remotion_isReadOnlyStudio ||+ getBrowserStudioEffectOperations() !== null;diff --git a/packages/studio/src/test/browser-studio-effects.test.ts b/packages/studio/src/test/browser-studio-effects.test.tsnew file mode 100644index 0000000000..0d864f1d9d--- /dev/null+++ b/packages/studio/src/test/browser-studio-effects.test.ts@@ -0,0 +1,162 @@+import {afterEach, expect, test} from 'bun:test';+import type {BrowserStudioEffectOperations} from '@remotion/studio-shared';+import {+ addEffect,+ deleteEffects,+ duplicateEffects,+ pasteEffects,+ reorderEffect,+ saveEffectProps,+ saveMultipleEffectProps,+} from '../components/effect-operations-api';+import {canUseEffectOperations} from '../helpers/browser-studio-operations';+import {makeBrowserStudioOperations} from './make-browser-studio-operations';++const originalWindowDescriptor = Object.getOwnPropertyDescriptor(+ globalThis,+ 'window',+);++afterEach(() => {+ if (originalWindowDescriptor) {+ Object.defineProperty(globalThis, 'window', originalWindowDescriptor);+ return;+ }++ Reflect.deleteProperty(globalThis, 'window');+});++test('routes effect mutations through the explicit Browser Studio capability', async () => {+ const calls: string[] = [];+ const effects: BrowserStudioEffectOperations = {+ addEffect: (request) => {+ calls.push(`add:${request.effectName}`);+ return Promise.resolve({success: true});+ },+ deleteEffects: (request) => {+ calls.push(`delete:${request.length}`);+ return Promise.resolve({success: true});+ },+ duplicateEffects: (request) => {+ calls.push(`duplicate:${request.length}`);+ return Promise.resolve({success: true});+ },+ pasteEffects: (request) => {+ calls.push(`paste:${request.effects.length}`);+ return Promise.resolve({success: true});+ },+ reorderEffect: (request) => {+ calls.push(`reorder:${request.fromIndex}:${request.toIndex}`);+ return Promise.resolve({success: true});+ },+ saveEffectProps: (request) => {+ calls.push(`save:${request.key}`);+ return Promise.resolve({+ canUpdate: true,+ callee: 'brightness',+ importPath: '@remotion/effects/brightness',+ effectIndex: request.effectIndex,+ props: {},+ });+ },+ saveMultipleEffectProps: (request) => {+ calls.push(`save-multiple:${request.edits.length}`);+ return Promise.resolve({results: []});+ },+ };+ Object.defineProperty(globalThis, 'window', {+ configurable: true,+ value: {+ remotion_browserStudio: makeBrowserStudioOperations({effects}),+ remotion_isReadOnlyStudio: true,+ },+ });+ const nodePath = {+ absolutePath: '/project/src/Comp.tsx',+ nodePath: ['program', 'body', 1],+ sequenceKeys: [],+ effectKeys: [['amount']],+ videoConfigValues: null,+ };+ const schema = {+ amount: {type: 'number' as const, default: 1, hiddenFromList: false},+ };++ expect(canUseEffectOperations()).toBe(true);+ await addEffect({+ fileName: 'src/Comp.tsx',+ sequenceNodePath: nodePath,+ effectName: 'brightness',+ effectImportPath: '@remotion/effects/brightness',+ effectConfig: {amount: 1},+ clientId: 'browser-studio',+ });+ await duplicateEffects([+ {+ fileName: 'src/Comp.tsx',+ sequenceNodePath: nodePath,+ effectIndex: 0,+ },+ ]);+ await reorderEffect({+ fileName: 'src/Comp.tsx',+ sequenceNodePath: nodePath,+ fromIndex: 0,+ toIndex: 1,+ clientId: 'browser-studio',+ });+ await saveEffectProps({+ type: 'value',+ fileName: 'src/Comp.tsx',+ sequenceNodePath: nodePath,+ effectIndex: 0,+ key: 'amount',+ value: '0.5',+ defaultValue: '1',+ schema,+ clientId: 'browser-studio',+ });+ await saveMultipleEffectProps({+ edits: [],+ clientId: 'browser-studio',+ undoLabel: 'Undo effect edit',+ redoLabel: 'Redo effect edit',+ });+ await pasteEffects({+ targetFileName: 'src/Comp.tsx',+ targetSequenceNodePath: nodePath,+ type: 'effects-additive',+ effects: [],+ clientId: 'browser-studio',+ insertAtIndices: null,+ });+ await deleteEffects([+ {+ type: 'single-effect',+ fileName: 'src/Comp.tsx',+ sequenceNodePath: nodePath,+ effectIndex: 0,+ },+ ]);++ expect(calls).toEqual([+ 'add:brightness',+ 'duplicate:1',+ 'reorder:0:1',+ 'save:amount',+ 'save-multiple:0',+ 'paste:0',+ 'delete:1',+ ]);+});++test('reports the capability as unavailable for an older Browser Studio host', () => {+ Object.defineProperty(globalThis, 'window', {+ configurable: true,+ value: {+ remotion_browserStudio: makeBrowserStudioOperations({}),+ remotion_isReadOnlyStudio: true,+ },+ });+ expect(canUseEffectOperations()).toBe(false);+});