Skip to content

🎥 Make videos programmatically with React

Save effect operations without Prettier

Jonny Burger7fd2e2882c33
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index 3dd7c5e36a..8f0d4958bd 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -890,7 +890,6 @@ export const createBrowserStudioOperations = ({
effectConfig: request.effectConfig,
effectImportPath: request.effectImportPath,
effectName: request.effectName,
- formatFile: formatCodemodFile,
input: project.files[absolutePath],
sequenceNodePath: request.sequenceNodePath.nodePath,
});
@@ -952,7 +951,6 @@ export const createBrowserStudioOperations = ({
absolutePath,
result: await deleteEffectsCodemod({
effects: targets,
- formatFile: formatCodemodFile,
input: project.files[absolutePath],
}),
})),
@@ -1011,7 +1009,6 @@ export const createBrowserStudioOperations = ({
absolutePath,
result: await duplicateEffectsCodemod({
effects: targets,
- formatFile: formatCodemodFile,
input: project.files[absolutePath],
}),
})),
@@ -1061,7 +1058,6 @@ export const createBrowserStudioOperations = ({
});
const result = await pasteEffectsCodemod({
effects: request.effects,
- formatFile: formatCodemodFile,
input: project.files[absolutePath],
insertAtIndices: request.insertAtIndices,
targetSequenceNodePath: request.targetSequenceNodePath.nodePath,
@@ -1089,7 +1085,6 @@ export const createBrowserStudioOperations = ({
project,
});
const result = await reorderEffectCodemod({
- formatFile: formatCodemodFile,
fromIndex: request.fromIndex,
input: project.files[absolutePath],
sequenceNodePath: request.sequenceNodePath.nodePath,
@@ -1117,7 +1112,6 @@ export const createBrowserStudioOperations = ({
});
const result = await updateEffectPropsCodemod({
effectIndex: request.effectIndex,
- formatFile: formatCodemodFile,
input: project.files[absolutePath],
schema: request.schema,
sequenceNodePath: request.sequenceNodePath.nodePath,
@@ -1172,7 +1166,6 @@ export const createBrowserStudioOperations = ({
});
const result = await updateEffectPropsCodemod({
effectIndex: edit.effectIndex,
- formatFile: formatCodemodFile,
input: outputByPath.get(absolutePath) ?? project.files[absolutePath],
schema: edit.schema,
sequenceNodePath: edit.sequenceNodePath.nodePath,
diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.ts
index fbbdf1f9d7..3fc47dca41 100644
--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts
@@ -1693,6 +1693,8 @@ test('mutates effects in the virtual project and reports structured failures', a
import {contrast} from '@remotion/effects/contrast';
import {AbsoluteFill} from 'remotion';
+const unrelated = {keep:"this spacing"}
+
export const Comp = () => (
<AbsoluteFill effects={[brightness({amount: 1}), contrast({amount: 2})]} />
);
@@ -1719,7 +1721,7 @@ export const Comp = () => (
});
const subscription = await operations.subscribeToSequenceProps({
fileName: 'src/Comp.tsx',
- line: 6,
+ line: 8,
column: 2,
nodePath: null,
componentIdentity: null,
@@ -1857,6 +1859,9 @@ export const Comp = () => (
expect(await operations.redo()).toMatchObject({success: true});
expect(currentProject.files[fileName].indexOf('tint({')).toBe(-1);
expect(projectChanges).toBeGreaterThanOrEqual(9);
+ expect(currentProject.files[fileName]).toContain(
+ 'const unrelated = {keep:"this spacing"}',
+ );
const beforeFailures = currentProject.files[fileName];
expect(
diff --git a/packages/studio-codemods/src/effect-operations.ts b/packages/studio-codemods/src/effect-operations.ts
index 37feb77b8d..d824e8c957 100644
--- a/packages/studio-codemods/src/effect-operations.ts
+++ b/packages/studio-codemods/src/effect-operations.ts
@@ -22,6 +22,12 @@ import {
ensureUseCurrentFrameHook,
findEnclosingFunctionPath,
} from './ensure-imports-and-frame-hook';
+import {
+ captureFunctionSourceSnapshots,
+ getFunctionSourceEditsForPrependedStatements,
+} from './function-source-edits';
+import {printJsxOpeningElement} from './print-jsx';
+import {recastLocToOffset} from './recast-loc-to-offset';
import {findJsxElementAtNodePath} from './sequence-props';
import {
findEffectCallExpression,
@@ -36,9 +42,31 @@ import {
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 {parseAst} from './sequence-props/parse-ast';
+import {
+ applySourceEdits,
+ captureImportSnapshots,
+ getInsertImportSourceEdits,
+ type SourceEdit,
+} from './source-edits';
+import {
+ getIndentationUnit,
+ getLineIndent,
+ getSourceFormattingConfig,
+ indentContinuationLines,
+ printNodeWithSourceStyle,
+} from './source-style';
import {parseValueExpression} from './update-nested-prop';
+export {
+ findEffectCallExpression,
+ findEffectsAttr,
+} from './sequence-props/can-update-effect-props';
+export {
+ enumerateEffectArrayElements,
+ type EffectArrayElement,
+} from './sequence-props/effect-array-elements';
+
const b = recast.types.builders;
const identifierRegex = /^[A-Za-z_$][0-9A-Za-z_$]*$/;
@@ -69,6 +97,13 @@ export type FormatEffectFile = (input: {contents: string}) => Promise<{
output: string;
}>;
+type EffectSourceStyleOptions = {
+ // Kept optional for compatibility with callers from before source edits
+ // replaced the full-file formatting pass.
+ formatFile?: FormatEffectFile;
+ prettierConfigOverride?: Record<string, unknown> | null;
+};
+
export type EffectTarget = {
sequenceNodePath: SequenceNodePath;
effectIndex: number;
@@ -86,8 +121,155 @@ export type EffectPropUpdate =
defaultValue: unknown | null;
};
-const formatAst = (ast: File, formatFile: FormatEffectFile) =>
- formatFile({contents: serializeAst(ast)});
+export type PropDelta = {
+ key: string;
+ valueString: string;
+};
+
+export type UpdateEffectPropsResult = {
+ output: string;
+ formatted: boolean;
+ oldValueString: string;
+ newValueString: string;
+ logLine: number;
+ effectCallee: string;
+ removedProps: PropDelta[];
+};
+
+type EffectSourceSnapshots = {
+ functionSnapshots: ReturnType<typeof captureFunctionSourceSnapshots>;
+ importSnapshots: ReturnType<typeof captureImportSnapshots>;
+ originalAttributeSources: Map<object, string>;
+ openingElementLocations: Map<JSXOpeningElement, JSXOpeningElement['loc']>;
+};
+
+const captureEffectSourceSnapshots = (ast: File): EffectSourceSnapshots => ({
+ functionSnapshots: captureFunctionSourceSnapshots(ast),
+ importSnapshots: captureImportSnapshots(ast),
+ originalAttributeSources: new Map(),
+ openingElementLocations: new Map(),
+});
+
+const trackOpeningElement = ({
+ jsx,
+ snapshots,
+}: {
+ jsx: JSXOpeningElement;
+ snapshots: EffectSourceSnapshots;
+}) => {
+ if (!snapshots.openingElementLocations.has(jsx)) {
+ snapshots.openingElementLocations.set(jsx, jsx.loc);
+ for (const attribute of jsx.attributes) {
+ snapshots.originalAttributeSources.set(
+ attribute,
+ recast.print(attribute).code,
+ );
+ }
+ }
+};
+
+const getEffectSourceOutput = ({
+ ast,
+ input,
+ prettierConfigOverride,
+ snapshots,
+}: {
+ ast: File;
+ input: string;
+ prettierConfigOverride: Record<string, unknown> | null;
+ snapshots: EffectSourceSnapshots;
+}) => {
+ const formattingConfig = getSourceFormattingConfig({
+ input,
+ prettierConfigOverride,
+ });
+ const {coveredRanges, edits: functionEdits} =
+ getFunctionSourceEditsForPrependedStatements({
+ indentationUnit: formattingConfig.indentationUnit,
+ input,
+ printNode: (node) =>
+ printNodeWithSourceStyle({
+ input,
+ node,
+ prettierConfigOverride: formattingConfig,
+ wrapColumn: formattingConfig.printWidth,
+ }),
+ reprintBlockBodies: new Set(),
+ snapshots: snapshots.functionSnapshots,
+ });
+ const isCoveredByFunctionEdit = (start: number, end: number) =>
+ coveredRanges.some((range) => start >= range.start && end <= range.end);
+ const getJsxSourceIndent = (offset: number) => {
+ const lineStart = input.lastIndexOf('\n', offset - 1) + 1;
+ const startsInsideSameLineFunctionBlock = snapshots.functionSnapshots.some(
+ ({body}) => {
+ if (body.type !== 'BlockStatement' || !body.loc) {
+ return false;
+ }
+
+ const blockStart = recastLocToOffset(input, body.loc.start);
+ const blockEnd = recastLocToOffset(input, body.loc.end);
+ return (
+ blockStart < offset &&
+ offset < blockEnd &&
+ input.lastIndexOf('\n', blockStart - 1) + 1 === lineStart
+ );
+ },
+ );
+ const lineIndent = getLineIndent({input, offset});
+ return startsInsideSameLineFunctionBlock
+ ? `${lineIndent}${getIndentationUnit(input, prettierConfigOverride)}`
+ : lineIndent;
+ };
+
+ const openingElementEdits: SourceEdit[] = [];
+ for (const [openingElement, location] of snapshots.openingElementLocations) {
+ if (!location) {
+ throw new Error('Cannot update effect without a JSX source location');
+ }
+
+ const start = recastLocToOffset(input, location.start);
+ const end = recastLocToOffset(input, location.end);
+ if (isCoveredByFunctionEdit(start, end)) {
+ continue;
+ }
+
+ const original = input.slice(start, end);
+ if (recast.print(openingElement).code === original) {
+ continue;
+ }
+
+ const replacement = indentContinuationLines({
+ indent: getJsxSourceIndent(start),
+ input,
+ printed: printJsxOpeningElement({
+ openingElement: openingElement as never,
+ input,
+ originalAttributeSources: snapshots.originalAttributeSources,
+ prettierConfigOverride: formattingConfig,
+ }),
+ }).replace(/^[\t ]+(?=\r?$)/gm, '');
+ openingElementEdits.push({
+ start,
+ end,
+ replacement,
+ });
+ }
+
+ return applySourceEdits({
+ input,
+ edits: [
+ ...getInsertImportSourceEdits({
+ ast,
+ input,
+ prettierConfigOverride: formattingConfig,
+ snapshots: snapshots.importSnapshots,
+ }),
+ ...functionEdits,
+ ...openingElementEdits,
+ ],
+ });
+};
const getEffectsArray = (attr: JSXAttribute, action: string) => {
if (!attr.value || attr.value.type !== 'JSXExpressionContainer') {
@@ -127,7 +309,7 @@ const getJsx = ({
return jsx;
};
-const assertValidEffect = ({
+export const assertValidEffect = ({
effectImportPath,
effectName,
}: {
@@ -170,7 +352,7 @@ const hasTopLevelBinding = (ast: File, name: string) =>
);
});
-const ensureEffectImport = ({
+export const ensureEffectImport = ({
ast,
effectImportPath,
effectName,
@@ -197,7 +379,7 @@ const ensureEffectImport = ({
});
};
-const makeConfigObject = (config: Record<string, unknown>) =>
+export const makeConfigObjectExpression = (config: Record<string, unknown>) =>
b.objectExpression(
Object.entries(config).map(([key, value]) =>
b.objectProperty(
@@ -207,192 +389,318 @@ const makeConfigObject = (config: Record<string, unknown>) =>
) as never,
) as ObjectExpression;
-export const addEffect = async ({
+export const addEffect = ({
effectConfig,
effectImportPath,
effectName,
- formatFile,
input,
+ prettierConfigOverride,
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,
- ),
- );
- }
+} & EffectSourceStyleOptions): Promise<{
+ output: string;
+ formatted: boolean;
+ effectLabel: string;
+ nodeLabel: string;
+ logLine: number;
+}> =>
+ Promise.resolve().then(() => {
+ assertValidEffect({effectImportPath, effectName});
+ const ast = parseAst(input);
+ const snapshots = captureEffectSourceSnapshots(ast);
+ const jsx = getJsx({action: 'add', ast, sequenceNodePath});
+ trackOpeningElement({jsx, snapshots});
+ const localName = ensureEffectImport({ast, effectImportPath, effectName});
+ const effectCall = b.callExpression(b.identifier(localName), [
+ makeConfigObjectExpression(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;
-};
+ return {
+ output: getEffectSourceOutput({
+ ast,
+ input,
+ prettierConfigOverride: prettierConfigOverride ?? null,
+ snapshots,
+ }),
+ formatted: true,
+ effectLabel: `${effectName}()`,
+ nodeLabel:
+ jsx.name.type === 'JSXIdentifier' ? `<${jsx.name.name}>` : 'element',
+ logLine: jsx.loc?.start.line ?? 1,
+ };
+ });
-export const duplicateEffects = async ({
+export const duplicateEffects = ({
effects,
- formatFile,
input,
+ prettierConfigOverride,
}: {
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');
+} & EffectSourceStyleOptions): Promise<{
+ output: string;
+ formatted: boolean;
+ effectLabels: string[];
+ logLines: number[];
+}> =>
+ Promise.resolve().then(() => {
+ if (effects.length === 0) {
+ throw new Error('No effects were specified for duplication');
}
- const found = findEffectCallExpression({attr, effectIndex});
- if (found.kind === 'error') {
- throw new Error(`Cannot duplicate effect: ${found.reason}`);
- }
+ const ast = parseAst(input);
+ const snapshots = captureEffectSourceSnapshots(ast);
+ const effectsByAttribute = new Map<
+ JSXAttribute,
+ {
+ array: ArrayExpression;
+ indices: Set<number>;
+ effectLabels: string[];
+ logLines: 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 group = effectsByAttribute.get(attr) ?? {
- array: getEffectsArray(attr, 'duplicate'),
- indices: new Set<number>(),
- };
- group.indices.add(effectIndex);
- effectsByAttribute.set(attr, group);
- }
+ const array = getEffectsArray(attr, 'duplicate');
+ const found = findEffectCallExpression({attr, effectIndex});
+ if (found.kind === 'error') {
+ throw new Error(`Cannot duplicate effect: ${found.reason}`);
+ }
- 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');
+ const group = effectsByAttribute.get(attr) ?? {
+ array,
+ indices: new Set<number>(),
+ effectLabels: [],
+ logLines: [],
+ };
+ effectsByAttribute.set(attr, group);
+ trackOpeningElement({jsx, snapshots});
+ if (group.indices.has(effectIndex)) {
+ continue;
}
- array.elements.splice(effectIndex + 1, 0, cloneAstValue(effect) as never);
+ group.indices.add(effectIndex);
+ group.effectLabels.push(`${found.callee}()`);
+ group.logLines.push(
+ found.call.loc?.start.line ?? jsx.loc?.start.line ?? 1,
+ );
}
- }
- const formatted = await formatAst(ast, formatFile);
- return formatted;
-};
+ 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,
+ );
+ }
+ }
+
+ return {
+ output: getEffectSourceOutput({
+ ast,
+ input,
+ prettierConfigOverride: prettierConfigOverride ?? null,
+ snapshots,
+ }),
+ formatted: true,
+ effectLabels: [...effectsByAttribute.values()].flatMap(
+ (group) => group.effectLabels,
+ ),
+ logLines: [...effectsByAttribute.values()].flatMap(
+ (group) => group.logLines,
+ ),
+ };
+ });
-export const reorderEffect = async ({
- formatFile,
+export const duplicateEffect = ({
+ effectIndex,
+ input,
+ prettierConfigOverride,
+ sequenceNodePath,
+}: {
+ effectIndex: number;
+ input: string;
+ sequenceNodePath: SequenceNodePath;
+} & EffectSourceStyleOptions): Promise<{
+ output: string;
+ formatted: boolean;
+ effectLabel: string;
+ logLine: number;
+}> =>
+ duplicateEffects({
+ input,
+ effects: [{effectIndex, sequenceNodePath}],
+ prettierConfigOverride,
+ }).then(({effectLabels, formatted, logLines, output}) => ({
+ output,
+ formatted,
+ effectLabel: effectLabels[0],
+ logLine: logLines[0],
+ }));
+
+export const reorderEffect = ({
fromIndex,
input,
+ prettierConfigOverride,
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');
- }
+} & EffectSourceStyleOptions): Promise<{
+ output: string;
+ formatted: boolean;
+ effectLabel: string;
+ logLine: number;
+}> =>
+ Promise.resolve().then(() => {
+ const ast = parseAst(input);
+ const snapshots = captureEffectSourceSnapshots(ast);
+ 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');
- }
+ 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 (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',
- );
- }
+ const target = elements[fromIndex];
+ if (target.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);
- }
+ trackOpeningElement({jsx, snapshots});
+ 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;
-};
+ return {
+ output: getEffectSourceOutput({
+ ast,
+ input,
+ prettierConfigOverride: prettierConfigOverride ?? null,
+ snapshots,
+ }),
+ formatted: true,
+ effectLabel: `${target.callee}()`,
+ logLine: target.node.loc?.start.line ?? jsx.loc?.start.line ?? 1,
+ };
+ });
-export const deleteEffects = async ({
+export const deleteEffects = ({
effects,
- formatFile,
input,
+ prettierConfigOverride,
}: {
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');
+} & EffectSourceStyleOptions): Promise<{
+ output: string;
+ formatted: boolean;
+ effectLabels: string[];
+ logLines: number[];
+}> =>
+ Promise.resolve().then(() => {
+ if (effects.length === 0) {
+ throw new Error('No effects were specified for deletion');
}
- 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');
+ const ast = parseAst(input);
+ const snapshots = captureEffectSourceSnapshots(ast);
+ const effectsByAttribute = new Map<
+ JSXAttribute,
+ {
+ all: boolean;
+ array: ArrayExpression;
+ attributes: JSXOpeningElement['attributes'];
+ indices: Set<number>;
+ effectLabels: string[];
+ logLines: 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');
}
- group.all = true;
- group.indices.clear();
- continue;
- }
+ const group = effectsByAttribute.get(attr) ?? {
+ all: false,
+ array: getEffectsArray(attr, 'delete'),
+ attributes: jsx.attributes,
+ indices: new Set<number>(),
+ effectLabels: [],
+ logLines: [],
+ };
+ effectsByAttribute.set(attr, group);
+ trackOpeningElement({jsx, snapshots});
+ if (effect.type === 'all-effects') {
+ if (group.array.elements.length === 0) {
+ throw new Error('Cannot delete effect: no effects found');
+ }
+
+ const elements = enumerateEffectArrayElements(group.array);
+ group.all = true;
+ group.indices.clear();
+ group.effectLabels = elements.map((element) =>
+ element.kind === 'call' ? `${element.callee}()` : 'effect',
+ );
+ group.logLines = elements.map((element) =>
+ element.kind === 'call'
+ ? (element.node.loc?.start.line ?? attr.loc?.start.line ?? 1)
+ : (attr.loc?.start.line ?? 1),
+ );
+ continue;
+ }
+
+ if (group.all || group.indices.has(effect.effectIndex)) {
+ continue;
+ }
- if (!group.all && !group.indices.has(effect.effectIndex)) {
const found = findEffectCallExpression({
attr,
effectIndex: effect.effectIndex,
@@ -402,27 +710,71 @@ export const deleteEffects = async ({
}
group.indices.add(effect.effectIndex);
+ group.effectLabels.push(`${found.callee}()`);
+ group.logLines.push(
+ found.call.loc?.start.line ?? jsx.loc?.start.line ?? 1,
+ );
}
- }
- 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);
+ 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);
+ 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;
-};
+ return {
+ output: getEffectSourceOutput({
+ ast,
+ input,
+ prettierConfigOverride: prettierConfigOverride ?? null,
+ snapshots,
+ }),
+ formatted: true,
+ effectLabels: [...effectsByAttribute.values()].flatMap(
+ (group) => group.effectLabels,
+ ),
+ logLines: [...effectsByAttribute.values()].flatMap(
+ (group) => group.logLines,
+ ),
+ };
+ });
+
+export const deleteEffect = ({
+ effectIndex,
+ input,
+ prettierConfigOverride,
+ sequenceNodePath,
+}: {
+ effectIndex: number;
+ input: string;
+ sequenceNodePath: SequenceNodePath;
+} & EffectSourceStyleOptions): Promise<{
+ output: string;
+ formatted: boolean;
+ effectLabel: string;
+ logLine: number;
+}> =>
+ deleteEffects({
+ input,
+ effects: [{type: 'single-effect', effectIndex, sequenceNodePath}],
+ prettierConfigOverride,
+ }).then(({effectLabels, formatted, logLines, output}) => ({
+ output,
+ formatted,
+ effectLabel: effectLabels[0],
+ logLine: logLines[0],
+ }));
const makeEffectCall = ({
ast,
@@ -472,100 +824,116 @@ const ensureFrameHook = ({
}
};
-export const pasteEffects = async ({
+export const pasteEffects = ({
effects,
- formatFile,
input,
insertAtIndices,
+ prettierConfigOverride,
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({
+} & EffectSourceStyleOptions): Promise<{
+ output: string;
+ formatted: boolean;
+ effectLabels: string[];
+ logLine: number;
+}> =>
+ Promise.resolve().then(() => {
+ const ast = parseAst(input);
+ const snapshots = captureEffectSourceSnapshots(ast);
+ const jsx = getJsx({
+ action: 'paste',
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);
+ trackOpeningElement({jsx, snapshots});
+ const requiredImports = getRequiredRemotionImportsForClipboardParams(
+ effects.flatMap((effect) => Object.values(effect.params)),
+ );
+ const localNames = ensureClipboardParamRemotionImports({
+ ast,
+ requiredImports,
+ });
+ if (requiredImports.has('useCurrentFrame')) {
+ ensureFrameHook({
+ ast,
+ localNames,
+ sequenceNodePath: targetSequenceNodePath,
+ });
}
- if (calls.length > 0) {
- jsx.attributes.push(
- makeEffectsAttr(b.arrayExpression(calls as never) as ArrayExpression),
- );
+ 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');
}
- } 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']),
- );
+
+ 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 {
- 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);
- }
+ 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,
- ),
- );
+ if (!existingAttr) {
+ jsx.attributes.push(
+ makeEffectsAttr(
+ b.arrayExpression(elements as never) as ArrayExpression,
+ ),
+ );
+ }
}
- }
- const formatted = await formatAst(ast, formatFile);
- return formatted;
-};
+ return {
+ output: getEffectSourceOutput({
+ ast,
+ input,
+ prettierConfigOverride: prettierConfigOverride ?? null,
+ snapshots,
+ }),
+ formatted: true,
+ effectLabels: effects.map((effect) => `${effect.callee}()`),
+ logLine: jsx.loc?.start.line ?? 1,
+ };
+ });
const isEffectParamUpdate = (
update: EffectPropUpdate,
@@ -581,6 +949,29 @@ const findObjectProperty = (object: ObjectExpression, key: string) =>
(property.key as StringLiteral).value === key)),
);
+const printObjectPropertyValue = (property: ObjectProperty) =>
+ recast
+ .print(property.value)
+ .code.replace(/[\n\r\t]+/g, ' ')
+ .replace(/,(\s*[}\]])/g, '$1')
+ .trim();
+
+const removeObjectProperty = ({
+ key,
+ object,
+}: {
+ key: string;
+ object: ObjectExpression;
+}): PropDelta | null => {
+ const property = findObjectProperty(object, key);
+ if (!property) {
+ return null;
+ }
+
+ object.properties.splice(object.properties.indexOf(property), 1);
+ return {key, valueString: printObjectPropertyValue(property)};
+};
+
const makeEffectPropExpression = ({
ast,
sequenceNodePath,
@@ -608,23 +999,32 @@ const makeEffectPropExpression = ({
return makeClipboardParamExpression({param: update.effectParam, localNames});
};
-export const updateEffectProps = async ({
+export const updateEffectPropsAst = ({
effectIndex,
- formatFile,
input,
+ prettierConfigOverride,
schema,
sequenceNodePath,
update,
}: {
effectIndex: number;
- formatFile: FormatEffectFile;
input: string;
+ prettierConfigOverride?: Record<string, unknown> | null;
schema: InteractivitySchema;
sequenceNodePath: SequenceNodePath;
update: EffectPropUpdate;
-}) => {
+}): {
+ serialized: string;
+ oldValueString: string;
+ newValueString: string;
+ logLine: number;
+ effectCallee: string;
+ removedProps: PropDelta[];
+} => {
const ast = parseAst(input);
+ const snapshots = captureEffectSourceSnapshots(ast);
const jsx = getJsx({action: 'update', ast, sequenceNodePath});
+ trackOpeningElement({jsx, snapshots});
const attr = findEffectsAttr(jsx.attributes);
if (!attr) {
throw new Error('Could not find effects on the target JSX element');
@@ -635,32 +1035,49 @@ export const updateEffectProps = async ({
throw new Error(`Cannot update effect prop: ${found.reason}`);
}
+ const {call, callee: effectCallee} = found;
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 (call.arguments.length === 0) {
if (isDefault) {
- const unchangedFormatted = await formatAst(ast, formatFile);
- return unchangedFormatted;
+ return {
+ serialized: input,
+ oldValueString: '',
+ newValueString: JSON.stringify(update.defaultValue),
+ logLine: call.loc?.start.line ?? jsx.loc?.start.line ?? 1,
+ effectCallee,
+ removedProps: [],
+ };
}
object = b.objectExpression([]) as ObjectExpression;
- found.call.arguments.push(object);
- } else if (found.call.arguments[0].type !== 'ObjectExpression') {
+ call.arguments.push(object);
+ } else if (call.arguments[0].type !== 'ObjectExpression') {
throw new Error('Cannot update effect prop: computed');
} else {
- object = found.call.arguments[0] as ObjectExpression;
+ object = call.arguments[0] as ObjectExpression;
}
const existing = findObjectProperty(object, update.key);
+ let oldValueString = '';
+ if (existing) {
+ oldValueString = recast.print(existing.value).code;
+ } else if (update.defaultValue !== null) {
+ oldValueString = JSON.stringify(update.defaultValue);
+ }
+
+ let newValueString = '';
if (isDefault) {
+ newValueString = JSON.stringify(update.defaultValue);
if (existing) {
object.properties.splice(object.properties.indexOf(existing), 1);
}
} else {
const value = makeEffectPropExpression({ast, sequenceNodePath, update});
+ newValueString = recast.print(value).code;
if (existing) {
existing.value = value as ObjectProperty['value'];
} else {
@@ -676,19 +1093,73 @@ export const updateEffectProps = async ({
: null
: update.value;
const field = schema[update.key];
+ const removedProps: PropDelta[] = [];
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 removed = removeObjectProperty({key, object});
+ if (removed) {
+ removedProps.push(removed);
}
}
}
- const formatted = await formatAst(ast, formatFile);
- return formatted;
+ return {
+ serialized: getEffectSourceOutput({
+ ast,
+ input,
+ prettierConfigOverride: prettierConfigOverride ?? null,
+ snapshots,
+ }),
+ oldValueString,
+ newValueString,
+ logLine: call.loc?.start.line ?? jsx.loc?.start.line ?? 1,
+ effectCallee,
+ removedProps,
+ };
};
+
+export const updateEffectProps = ({
+ effectIndex,
+ input,
+ prettierConfigOverride,
+ schema,
+ sequenceNodePath,
+ update,
+}: {
+ effectIndex: number;
+ input: string;
+ schema: InteractivitySchema;
+ sequenceNodePath: SequenceNodePath;
+ update: EffectPropUpdate;
+} & EffectSourceStyleOptions): Promise<UpdateEffectPropsResult> =>
+ Promise.resolve().then(() => {
+ const {
+ serialized,
+ oldValueString,
+ newValueString,
+ logLine,
+ effectCallee,
+ removedProps,
+ } = updateEffectPropsAst({
+ input,
+ sequenceNodePath,
+ effectIndex,
+ update,
+ schema,
+ prettierConfigOverride,
+ });
+
+ return {
+ output: serialized,
+ formatted: true,
+ oldValueString,
+ newValueString,
+ logLine,
+ effectCallee,
+ removedProps,
+ };
+ });
diff --git a/packages/studio-codemods/src/function-source-edits.ts b/packages/studio-codemods/src/function-source-edits.ts
index d14167d5da..dee4ae0d5f 100644
--- a/packages/studio-codemods/src/function-source-edits.ts
+++ b/packages/studio-codemods/src/function-source-edits.ts
@@ -153,6 +153,118 @@ export const getFunctionSourceEditsForPrependedStatements = ({
continue;
}
+ const returnStatement =
+ functionNode.body.type === 'BlockStatement'
+ ? functionNode.body.body.at(-1)
+ : null;
+ let expressionHasJsxComment = false;
+ if (originalBody.type !== 'BlockStatement') {
+ recast.types.visit(originalBody, {
+ visitJSXExpressionContainer(path) {
+ if (path.node.expression.type === 'JSXEmptyExpression') {
+ expressionHasJsxComment = true;
+ return false;
+ }
+
+ this.traverse(path);
+ return undefined;
+ },
+ });
+ }
+
+ if (
+ originalBody.type !== 'BlockStatement' &&
+ expressionHasJsxComment &&
+ functionNode.type === 'ArrowFunctionExpression' &&
+ functionNode.body.type === 'BlockStatement' &&
+ returnStatement?.type === 'ReturnStatement' &&
+ returnStatement.argument === originalBody &&
+ functionNode.loc
+ ) {
+ const functionStart = recastLocToOffset(input, functionNode.loc.start);
+ const tokens = (
+ originalBody.loc as
+ | {
+ tokens?: {
+ loc?: {
+ end: {column: number; line: number};
+ start: {column: number; line: number};
+ };
+ type?: {label?: string};
+ }[];
+ }
+ | null
+ | undefined
+ )?.tokens;
+ const arrowToken = tokens?.findLast((token) => {
+ if (token.type?.label !== '=>' || !token.loc) {
+ return false;
+ }
+
+ const start = recastLocToOffset(input, token.loc.start);
+ const end = recastLocToOffset(input, token.loc.end);
+ return start >= functionStart && end <= range.start;
+ });
+ const arrowStart = arrowToken?.loc
+ ? recastLocToOffset(input, arrowToken.loc.start)
+ : input.lastIndexOf('=>', range.start);
+ if (arrowStart >= functionStart) {
+ const functionIndent = getLineIndent({input, offset: functionStart});
+ const expressionStatementIndent = `${functionIndent}${indentationUnit}`;
+ const bodyStart = originalBody.loc
+ ? recastLocToOffset(input, originalBody.loc.start)
+ : range.start;
+ let returnStart = range.start;
+ if (input[range.start] !== '(') {
+ const lastLeadingCommentEnd = (
+ originalBody.leadingComments ?? []
+ ).reduce<number | null>((latest, comment) => {
+ if (!comment.loc) {
+ return latest;
+ }
+
+ const end = recastLocToOffset(input, comment.loc.end);
+ return end <= bodyStart ? Math.max(latest ?? end, end) : latest;
+ }, null);
+ if (lastLeadingCommentEnd !== null) {
+ returnStart = lastLeadingCommentEnd;
+ while (returnStart < bodyStart && /\s/.test(input[returnStart])) {
+ returnStart++;
+ }
+ }
+ }
+
+ const prependedStatements = functionNode.body.body.slice(0, -1);
+ const printedPrependedStatements = prependedStatements
+ .map((statement) =>
+ indentContinuationLines({
+ indent: expressionStatementIndent,
+ input,
+ printed: printNode(statement as unknown as namedTypes.Node),
+ }),
+ )
+ .join(`${endOfLine}${expressionStatementIndent}`);
+ const returnTerminator = printNode(
+ returnStatement as unknown as namedTypes.Node,
+ )
+ .trimEnd()
+ .endsWith(';')
+ ? ';'
+ : '';
+ edits.push({
+ start: arrowStart,
+ end: returnStart,
+ replacement: `=> {${endOfLine}${expressionStatementIndent}${printedPrependedStatements}${prependedStatements.length === 0 ? '' : `${endOfLine}${expressionStatementIndent}`}${input.slice(range.start, returnStart)}return `,
+ });
+ edits.push({
+ start: range.end,
+ end: range.end,
+ replacement: `${returnTerminator}${endOfLine}${functionIndent}}`,
+ });
+ continue;
+ }
+ }
+
edits.push({
...range,
replacement: indentContinuationLines({
diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.ts
index 2407371b27..e5199a9279 100644
--- a/packages/studio-codemods/src/index.ts
+++ b/packages/studio-codemods/src/index.ts
@@ -28,15 +28,27 @@ export {
} from './duplicate-jsx-node';
export {
addEffect,
+ assertValidEffect,
+ deleteEffect,
deleteEffects,
+ duplicateEffect,
duplicateEffects,
+ ensureEffectImport,
+ enumerateEffectArrayElements,
+ findEffectCallExpression,
+ findEffectsAttr,
+ makeConfigObjectExpression,
pasteEffects,
reorderEffect,
updateEffectProps,
+ updateEffectPropsAst,
type EffectDeletionTarget,
+ type EffectArrayElement,
type EffectPropUpdate,
type EffectTarget,
type FormatEffectFile,
+ type PropDelta,
+ type UpdateEffectPropsResult,
} from './effect-operations';
export {
ensureRemotionImports,
diff --git a/packages/studio-codemods/src/print-jsx.ts b/packages/studio-codemods/src/print-jsx.ts
index 35916ef71a..3d0045cbb9 100644
--- a/packages/studio-codemods/src/print-jsx.ts
+++ b/packages/studio-codemods/src/print-jsx.ts
@@ -1,5 +1,6 @@
import type {namedTypes} from 'ast-types';
import * as recast from 'recast';
+import {recastLocToOffset} from './recast-loc-to-offset';
import {
getIndentationUnit,
getObjectCurlySpacing,
@@ -51,10 +52,12 @@ export const indentInsertedJsx = ({
export const printInsertedJsx = ({
element,
input,
+ originalAttributeSources,
prettierConfigOverride,
}: {
element: namedTypes.JSXElement | namedTypes.JSXFragment;
input: string;
+ originalAttributeSources?: ReadonlyMap<object, string>;
prettierConfigOverride: Record<string, unknown> | null;
}): string => {
const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';
@@ -118,6 +121,38 @@ export const printInsertedJsx = ({
typeof printWidth === 'number' ? printWidth : 80;
const name = printNode(opening.name, effectivePrintWidth);
const attributes = (opening.attributes ?? []).map((attribute) => {
+ const originalAttributeSource = originalAttributeSources?.get(attribute);
+ if (
+ originalAttributeSource === recast.print(attribute).code &&
+ attribute.loc
+ ) {
+ const start = recastLocToOffset(input, attribute.loc.start);
+ const end = recastLocToOffset(input, attribute.loc.end);
+ const original = input.slice(start, end);
+ const lines = original.split(/\r?\n/);
+ const nonBlankContinuationLines = lines
+ .slice(1)
+ .filter((line) => line.trim().length > 0);
+ let commonIndent =
+ nonBlankContinuationLines[0]?.match(/^\s*/)?.[0] ?? '';
+ for (const line of nonBlankContinuationLines.slice(1)) {
+ const indent = line.match(/^\s*/)?.[0] ?? '';
+ while (!indent.startsWith(commonIndent)) {
+ commonIndent = commonIndent.slice(0, -1);
+ }
+ }
+
+ return lines
+ .map((line, index) => {
+ if (line.trim().length === 0) {
+ return '';
+ }
+
+ return index === 0 ? line : line.slice(commonIndent.length);
+ })
+ .join(endOfLine);
+ }
+
if (
attribute.type === 'JSXAttribute' &&
attribute.name.type === 'JSXIdentifier' &&
@@ -249,10 +284,12 @@ export const printInsertedJsx = ({
export const printJsxOpeningElement = ({
openingElement,
input,
+ originalAttributeSources,
prettierConfigOverride,
}: {
openingElement: namedTypes.JSXOpeningElement;
input: string;
+ originalAttributeSources?: ReadonlyMap<object, string>;
prettierConfigOverride: Record<string, unknown> | null;
}): string => {
const wasSelfClosing = openingElement.selfClosing ?? false;
@@ -268,6 +305,7 @@ export const printJsxOpeningElement = ({
const printed = printInsertedJsx({
element: printableElement,
input,
+ originalAttributeSources,
prettierConfigOverride: {
bracketSpacing: getObjectCurlySpacing(input, prettierConfigOverride),
singleQuote:
diff --git a/packages/studio-codemods/src/test/effect-operations-formatting.test.ts b/packages/studio-codemods/src/test/effect-operations-formatting.test.ts
new file mode 100644
index 0000000000..ab69396b16
--- /dev/null
+++ b/packages/studio-codemods/src/test/effect-operations-formatting.test.ts
@@ -0,0 +1,320 @@
+import {expect, test} from 'bun:test';
+import * as recast from 'recast';
+import type {InteractivitySchema, SequenceNodePath} from 'remotion';
+import {
+ addEffect,
+ deleteEffects,
+ duplicateEffects,
+ pasteEffects,
+ reorderEffect,
+ updateEffectProps,
+} from '../effect-operations';
+import {getNodePathForRecastPath} from '../sequence-props';
+import {parseAst} from '../sequence-props/parse-ast';
+
+const getNodePathAtLine = (input: string, line: number): SequenceNodePath => {
+ const ast = parseAst(input);
+ let nodePath: SequenceNodePath | null = null;
+ recast.types.visit(ast, {
+ visitJSXOpeningElement(path) {
+ if (path.node.loc?.start.line === line) {
+ nodePath = getNodePathForRecastPath(path, ast);
+ return false;
+ }
+
+ return this.traverse(path);
+ },
+ });
+ if (!nodePath) {
+ throw new Error(`Could not find a JSX element on line ${line}`);
+ }
+
+ return nodePath;
+};
+
+const formatFile = () => {
+ throw new Error('The compatibility formatter must not be called');
+};
+
+const amountSchema = {
+ amount: {type: 'number', default: 1, hiddenFromList: false},
+} satisfies InteractivitySchema;
+
+test('effect operations preserve unrelated source without calling Prettier', async () => {
+ let output = `import { AbsoluteFill } from 'remotion'
+import { brightness } from '@remotion/effects/brightness'
+
+const unrelated = {keep:"this spacing"}
+
+export const Comp = () => (
+ <AbsoluteFill effects={[brightness({amount:1})]} />
+)
+`;
+ const sequenceNodePath = getNodePathAtLine(output, 7);
+
+ output = (
+ await addEffect({
+ input: output,
+ sequenceNodePath,
+ effectName: 'tint',
+ effectImportPath: '@remotion/effects/tint',
+ effectConfig: {color: 'red'},
+ formatFile,
+ })
+ ).output;
+ output = (
+ await duplicateEffects({
+ input: output,
+ effects: [{sequenceNodePath, effectIndex: 0}],
+ formatFile,
+ })
+ ).output;
+ output = (
+ await reorderEffect({
+ input: output,
+ sequenceNodePath,
+ fromIndex: 2,
+ toIndex: 0,
+ formatFile,
+ })
+ ).output;
+ output = (
+ await updateEffectProps({
+ input: output,
+ sequenceNodePath,
+ effectIndex: 1,
+ update: {key: 'amount', value: 2, defaultValue: null},
+ schema: amountSchema,
+ formatFile,
+ })
+ ).output;
+ output = (
+ await pasteEffects({
+ input: output,
+ targetSequenceNodePath: sequenceNodePath,
+ type: 'effects-additive',
+ effects: [
+ {
+ callee: 'blur',
+ importPath: '@remotion/effects/blur',
+ params: {radius: {type: 'static', value: 12}},
+ },
+ ],
+ insertAtIndices: null,
+ formatFile,
+ })
+ ).output;
+ output = (
+ await deleteEffects({
+ input: output,
+ effects: [{type: 'single-effect', sequenceNodePath, effectIndex: 2}],
+ formatFile,
+ })
+ ).output;
+
+ expect(output).toBe(`import { blur } from '@remotion/effects/blur'
+import { tint } from '@remotion/effects/tint'
+import { AbsoluteFill } from 'remotion'
+import { brightness } from '@remotion/effects/brightness'
+
+const unrelated = {keep:"this spacing"}
+
+export const Comp = () => (
+ <AbsoluteFill
+ effects={[tint({
+ color: 'red'
+ }), brightness({
+ amount: 2
+ }), blur({
+ radius: 12
+ })]}
+ />
+)
+`);
+});
+
+test('effect updates preserve blank lines in unrelated JSX object props', async () => {
+ const input = `import { Solid } from 'remotion'
+
+export const Comp = () => (
+ <Solid
+ style={{
+ amount: 3,
+
+ color: 'red',
+ }}
+ />
+)
+`;
+
+ const {output} = await addEffect({
+ input,
+ sequenceNodePath: getNodePathAtLine(input, 4),
+ effectName: 'brightness',
+ effectImportPath: '@remotion/effects/brightness',
+ effectConfig: {amount: 1},
+ formatFile,
+ });
+
+ expect(output).toBe(`import { brightness } from '@remotion/effects/brightness'
+import { Solid } from 'remotion'
+
+export const Comp = () => (
+ <Solid
+ style={{
+ amount: 3,
+
+ color: 'red',
+ }}
+ effects={[brightness({
+ amount: 1
+ })]}
+ />
+)
+`);
+});
+
+test('keyframed effect pastes preserve CRLF expression bodies and JSX comments', async () => {
+ const input = `'use client'
+import { HtmlInCanvas } from '@remotion/html-in-canvas'
+
+export const Comp = () => (
+ <HtmlInCanvas>
+ {/* keep me */}
+ content
+ </HtmlInCanvas>
+)
+`.replaceAll(/\r?\n/g, '\r\n');
+
+ const {output} = await pasteEffects({
+ input,
+ targetSequenceNodePath: getNodePathAtLine(input, 5),
+ type: 'effects-additive',
+ effects: [
+ {
+ callee: 'brightness',
+ importPath: '@remotion/effects/brightness',
+ params: {
+ amount: {
+ type: 'keyframed',
+ interpolationFunction: 'interpolate',
+ keyframes: [
+ {frame: 0, value: 0},
+ {frame: 30, value: 1},
+ ],
+ easing: [{type: 'linear'}],
+ clamping: {left: 'extend', right: 'extend'},
+ },
+ },
+ },
+ ],
+ insertAtIndices: null,
+ formatFile,
+ });
+
+ expect(output).toBe(
+ `'use client'
+import { useCurrentFrame, interpolate } from 'remotion'
+import { brightness } from '@remotion/effects/brightness'
+import { HtmlInCanvas } from '@remotion/html-in-canvas'
+
+export const Comp = () => {
+ const frame = useCurrentFrame()
+ return (
+ <HtmlInCanvas
+ effects={[brightness({
+ amount: interpolate(frame, [0, 30], [0, 1])
+ })]}
+ >
+ {/* keep me */}
+ content
+ </HtmlInCanvas>
+)
+}
+`.replaceAll(/\r?\n/g, '\r\n'),
+ );
+});
+
+test('no-op effect operations leave source byte-identical', async () => {
+ const input = `import { brightness } from '@remotion/effects/brightness'
+
+export const Comp = () => <div effects={[brightness()]} />
+`;
+ const sequenceNodePath = getNodePathAtLine(input, 3);
+ const reordered = await reorderEffect({
+ input,
+ sequenceNodePath,
+ fromIndex: 0,
+ toIndex: 0,
+ formatFile,
+ });
+ const updated = await updateEffectProps({
+ input: reordered.output,
+ sequenceNodePath,
+ effectIndex: 0,
+ update: {key: 'amount', value: 1, defaultValue: 1},
+ schema: amountSchema,
+ formatFile,
+ });
+
+ expect(updated.output).toBe(input);
+});
+
+test('batched duplicate and delete preserve source between distinct JSX elements', async () => {
+ const input = `import { brightness } from '@remotion/effects/brightness'
+
+const unrelated = {keep:"this spacing"}
+
+export const Comp = () => (
+ <>
+ <div effects={[brightness()]} />
+ {/* keep this oddly-spaced comment */}
+ <section effects={[brightness()]} />
+ </>
+)
+`;
+ const firstSequenceNodePath = getNodePathAtLine(input, 7);
+ const secondSequenceNodePath = getNodePathAtLine(input, 9);
+
+ const duplicated = await duplicateEffects({
+ input,
+ effects: [
+ {sequenceNodePath: firstSequenceNodePath, effectIndex: 0},
+ {sequenceNodePath: secondSequenceNodePath, effectIndex: 0},
+ ],
+ formatFile,
+ });
+
+ expect(duplicated.output)
+ .toBe(`import { brightness } from '@remotion/effects/brightness'
+
+const unrelated = {keep:"this spacing"}
+
+export const Comp = () => (
+ <>
+ <div effects={[brightness(), brightness()]} />
+ {/* keep this oddly-spaced comment */}
+ <section effects={[brightness(), brightness()]} />
+ </>
+)
+`);
+
+ const deleted = await deleteEffects({
+ input: duplicated.output,
+ effects: [
+ {
+ type: 'single-effect',
+ sequenceNodePath: firstSequenceNodePath,
+ effectIndex: 1,
+ },
+ {
+ type: 'single-effect',
+ sequenceNodePath: secondSequenceNodePath,
+ effectIndex: 1,
+ },
+ ],
+ formatFile,
+ });
+
+ expect(deleted.output).toBe(input);
+});
diff --git a/packages/studio-codemods/src/test/function-source-edits.test.ts b/packages/studio-codemods/src/test/function-source-edits.test.ts
index 52f9f50eef..a51c9e4c9c 100644
--- a/packages/studio-codemods/src/test/function-source-edits.test.ts
+++ b/packages/studio-codemods/src/test/function-source-edits.test.ts
@@ -8,6 +8,7 @@ import {
} from '../function-source-edits';
import {recastLocToOffset} from '../recast-loc-to-offset';
import {parseAst} from '../sequence-props/parse-ast';
+import {applySourceEdits} from '../source-edits';
const b = recast.types.builders;
@@ -108,3 +109,87 @@ test('filters edits nested inside a reprinted function body', () => {
expect(edits).toHaveLength(1);
expect(edits[0].start).toBe(input.indexOf('(', input.indexOf('=>')));
});
+
+test('preserves expression source when converting an arrow body to a block', () => {
+ const input =
+ `export const C = () => (\n <div>\n {/* keep me */}\n text\n </div>\n);\n`.replaceAll(
+ /\r?\n/g,
+ '\r\n',
+ );
+ const ast = parseAst(input);
+ const snapshots = captureFunctionSourceSnapshots(ast);
+ const functionNode = snapshots[0]?.functionNode;
+ if (
+ functionNode?.type !== 'ArrowFunctionExpression' ||
+ functionNode.body.type === 'BlockStatement'
+ ) {
+ throw new Error('Expected an expression-bodied arrow function');
+ }
+
+ const originalBody = functionNode.body;
+ functionNode.body = b.blockStatement([
+ b.variableDeclaration('const', [
+ b.variableDeclarator(
+ b.identifier('frame'),
+ b.callExpression(b.identifier('useCurrentFrame'), []),
+ ),
+ ]),
+ b.returnStatement(originalBody as Parameters<typeof b.returnStatement>[0]),
+ ]) as unknown as BlockStatement;
+
+ const {edits} = getFunctionSourceEditsForPrependedStatements({
+ indentationUnit: ' ',
+ input,
+ printNode: (node) => recast.prettyPrint(node).code,
+ reprintBlockBodies: new Set(),
+ snapshots,
+ });
+
+ expect(applySourceEdits({input, edits})).toBe(
+ `export const C = () => {\n const frame = useCurrentFrame();\n return (\n <div>\n {/* keep me */}\n text\n </div>\n);\n};\n`.replaceAll(
+ /\r?\n/g,
+ '\r\n',
+ ),
+ );
+});
+
+test('keeps a leading line comment before the inserted return', () => {
+ const input = `export const C = () => // keep with body
+ <div>{/* jsx */}</div>;
+`;
+ const ast = parseAst(input);
+ const snapshots = captureFunctionSourceSnapshots(ast);
+ const functionNode = snapshots[0]?.functionNode;
+ if (
+ functionNode?.type !== 'ArrowFunctionExpression' ||
+ functionNode.body.type === 'BlockStatement'
+ ) {
+ throw new Error('Expected an expression-bodied arrow function');
+ }
+
+ const originalBody = functionNode.body;
+ functionNode.body = b.blockStatement([
+ b.variableDeclaration('const', [
+ b.variableDeclarator(
+ b.identifier('frame'),
+ b.callExpression(b.identifier('useCurrentFrame'), []),
+ ),
+ ]),
+ b.returnStatement(originalBody as Parameters<typeof b.returnStatement>[0]),
+ ]) as unknown as BlockStatement;
+
+ const {edits} = getFunctionSourceEditsForPrependedStatements({
+ indentationUnit: ' ',
+ input,
+ printNode: (node) => recast.prettyPrint(node).code,
+ reprintBlockBodies: new Set(),
+ snapshots,
+ });
+
+ expect(applySourceEdits({input, edits})).toBe(`export const C = () => {
+ const frame = useCurrentFrame();
+ // keep with body
+ return <div>{/* jsx */}</div>;
+};
+`);
+});
diff --git a/packages/studio-server/src/codemods/add-effect.ts b/packages/studio-server/src/codemods/add-effect.ts
index 4a450fa49a..9525aba841 100644
--- a/packages/studio-server/src/codemods/add-effect.ts
+++ b/packages/studio-server/src/codemods/add-effect.ts
@@ -1,254 +1,6 @@
-import type {
- ArrayExpression,
- ClassDeclaration,
- Expression,
- File,
- FunctionDeclaration,
- JSXAttribute,
- JSXOpeningElement,
- ObjectExpression,
- ObjectProperty,
- VariableDeclaration,
-} from '@babel/types';
-import {stringifyDefaultProps} from '@remotion/studio-shared';
-import * as recast from 'recast';
-import type {SequenceNodePath} from 'remotion';
-import {ensureNamedImport} from '../helpers/imports';
-import {findJsxElementAtNodePath} from '../preview-server/routes/can-update-sequence-props';
-import {formatFileContent} from './format-file-content';
-import {parseAst, serializeAst} from './parse-ast';
-import {findEffectsAttr} from './update-effect-props/update-effect-props';
-
-const b = recast.types.builders;
-
-const identifierRegex = /^[A-Za-z_$][0-9A-Za-z_$]*$/;
-
-export const assertValidEffect = ({
- effectName,
- effectImportPath,
-}: {
- effectName: string;
- effectImportPath: string;
-}) => {
- if (!identifierRegex.test(effectName)) {
- throw new Error(`Invalid effect name "${effectName}"`);
- }
-
- const allowedImport =
- effectImportPath.startsWith('@remotion/effects/') ||
- effectImportPath === '@remotion/light-leaks' ||
- effectImportPath === '@remotion/starburst';
-
- if (!allowedImport) {
- throw new Error(`Unsupported effect import "${effectImportPath}"`);
- }
-};
-
-const parseValueExpression = (value: unknown): Expression => {
- const code = `a = ${stringifyDefaultProps({props: value, enumPaths: []})}`;
- const ast = parseAst(code);
- const stmt = ast.program.body[0];
- if (
- stmt.type !== 'ExpressionStatement' ||
- stmt.expression.type !== 'AssignmentExpression'
- ) {
- throw new Error('Failed to parse effect config value');
- }
-
- return stmt.expression.right as Expression;
-};
-
-const declarationBindsName = (
- declaration: ClassDeclaration | FunctionDeclaration | VariableDeclaration,
- name: string,
-) => {
- if (declaration.type === 'ClassDeclaration') {
- return declaration.id?.name === name;
- }
-
- if (declaration.type === 'FunctionDeclaration') {
- return declaration.id?.name === name;
- }
-
- return declaration.declarations.some((variableDeclaration) => {
- return (
- variableDeclaration.id.type === 'Identifier' &&
- variableDeclaration.id.name === name
- );
- });
-};
-
-const hasTopLevelBinding = ({ast, name}: {ast: File; name: string}) => {
- return ast.program.body.some((node) => {
- if (
- node.type === 'FunctionDeclaration' ||
- node.type === 'ClassDeclaration' ||
- node.type === 'VariableDeclaration'
- ) {
- return declarationBindsName(node, name);
- }
-
- if (
- node.type === 'ExportNamedDeclaration' &&
- node.declaration &&
- (node.declaration.type === 'FunctionDeclaration' ||
- node.declaration.type === 'ClassDeclaration' ||
- node.declaration.type === 'VariableDeclaration')
- ) {
- return declarationBindsName(node.declaration, name);
- }
-
- if (node.type !== 'ImportDeclaration') {
- return false;
- }
-
- return node.specifiers?.some((specifier) => specifier.local?.name === name);
- });
-};
-
-const getAvailableLocalName = ({
- ast,
- effectName,
-}: {
- ast: File;
- effectName: string;
-}) => {
- if (!hasTopLevelBinding({ast, name: effectName})) {
- return effectName;
- }
-
- const base = `${effectName}Effect`;
- if (!hasTopLevelBinding({ast, name: base})) {
- return base;
- }
-
- for (let i = 2; i < 100; i++) {
- const candidate = `${base}${i}`;
- if (!hasTopLevelBinding({ast, name: candidate})) {
- return candidate;
- }
- }
-
- throw new Error(`Cannot find a local name for ${effectName}`);
-};
-
-export const ensureEffectImport = ({
- ast,
- effectName,
- effectImportPath,
-}: {
- ast: File;
- effectName: string;
- effectImportPath: string;
-}) => {
- const localName = getAvailableLocalName({ast, effectName});
- return ensureNamedImport({
- ast,
- importedName: effectName,
- sourcePath: effectImportPath,
- localName,
- });
-};
-
-const getEffectsArray = (attr: JSXAttribute): ArrayExpression => {
- if (!attr.value || attr.value.type !== 'JSXExpressionContainer') {
- throw new Error('Cannot add effect: effects prop is not an array');
- }
-
- const expr = attr.value.expression as Expression;
- if (expr.type !== 'ArrayExpression') {
- throw new Error('Cannot add effect: effects prop is not an array');
- }
-
- return expr;
-};
-
-const makeEffectsAttr = (array: ArrayExpression): JSXAttribute => {
- return b.jsxAttribute(
- b.jsxIdentifier('effects'),
- b.jsxExpressionContainer(array as never),
- ) as unknown as JSXAttribute;
-};
-
-export const makeConfigObjectExpression = (
- config: Record<string, unknown>,
-): ObjectExpression => {
- return b.objectExpression(
- Object.entries(config).map(([key, value]) => {
- const keyNode = identifierRegex.test(key)
- ? b.identifier(key)
- : b.stringLiteral(key);
- return b.objectProperty(
- keyNode as never,
- parseValueExpression(value) as never,
- ) as unknown as ObjectProperty;
- }) as never,
- ) as unknown as ObjectExpression;
-};
-
-const getJsxTagLabel = (name: JSXOpeningElement['name']) => {
- if (name.type === 'JSXIdentifier') {
- return `<${name.name}>`;
- }
-
- return 'element';
-};
-
-export const addEffect = async ({
- input,
- sequenceNodePath,
- effectName,
- effectImportPath,
- effectConfig,
- prettierConfigOverride,
-}: {
- input: string;
- sequenceNodePath: SequenceNodePath;
- effectName: string;
- effectImportPath: string;
- effectConfig: Record<string, unknown>;
- prettierConfigOverride?: Record<string, unknown> | null;
-}): Promise<{
- output: string;
- formatted: boolean;
- effectLabel: string;
- nodeLabel: string;
- logLine: number;
-}> => {
- assertValidEffect({effectName, effectImportPath});
-
- const ast = parseAst(input);
- const jsx = findJsxElementAtNodePath(ast, sequenceNodePath);
- if (!jsx) {
- throw new Error(
- 'Could not find a JSX element at the specified location to add effect',
- );
- }
-
- const localName = ensureEffectImport({ast, effectName, effectImportPath});
- const effectCall = b.callExpression(b.identifier(localName), [
- makeConfigObjectExpression(effectConfig) as never,
- ]);
-
- const attr = findEffectsAttr(jsx.attributes ?? []);
- if (attr) {
- getEffectsArray(attr).elements.push(effectCall as never);
- } else {
- const effectsArray = b.arrayExpression([effectCall]) as ArrayExpression;
- jsx.attributes.push(makeEffectsAttr(effectsArray));
- }
-
- const finalFile = serializeAst(ast);
- const {output, formatted} = await formatFileContent({
- input: finalFile,
- prettierConfigOverride,
- });
-
- return {
- output,
- formatted,
- effectLabel: `${effectName}()`,
- nodeLabel: getJsxTagLabel(jsx.name),
- logLine: jsx.loc?.start.line ?? 1,
- };
-};
+export {
+ addEffect,
+ assertValidEffect,
+ ensureEffectImport,
+ makeConfigObjectExpression,
+} from '@remotion/studio-codemods';
diff --git a/packages/studio-server/src/codemods/delete-effect.ts b/packages/studio-server/src/codemods/delete-effect.ts
index beca88d8bb..071bbe9c97 100644
--- a/packages/studio-server/src/codemods/delete-effect.ts
+++ b/packages/studio-server/src/codemods/delete-effect.ts
@@ -1,220 +1,5 @@
-import type {
- ArrayExpression,
- Expression,
- JSXAttribute,
- JSXSpreadAttribute,
-} from '@babel/types';
-import type {SequenceNodePath} from 'remotion';
-import {findJsxElementAtNodePath} from '../preview-server/routes/can-update-sequence-props';
-import {formatFileContent} from './format-file-content';
-import {parseAst, serializeAst} from './parse-ast';
-import {
- enumerateEffectArrayElements,
- findEffectCallExpression,
- findEffectsAttr,
-} from './update-effect-props/update-effect-props';
-
-const getEffectsArray = (attr: JSXAttribute): ArrayExpression => {
- if (!attr.value || attr.value.type !== 'JSXExpressionContainer') {
- throw new Error('Cannot delete effect: effects prop is not an array');
- }
-
- const expr = attr.value.expression as Expression;
- if (expr.type !== 'ArrayExpression') {
- throw new Error('Cannot delete effect: effects prop is not an array');
- }
-
- return expr;
-};
-
-export type EffectDeletionTarget = {
- sequenceNodePath: SequenceNodePath;
-} & (
- | {
- type: 'single-effect';
- effectIndex: number;
- }
- | {
- type: 'all-effects';
- }
-);
-
-type EffectsArrayDeletion = {
- jsxAttributes: Array<JSXAttribute | JSXSpreadAttribute>;
- attr: JSXAttribute;
- effectsArray: ArrayExpression;
- allEffects: boolean;
- effectIndices: Set<number>;
- effectLabels: string[];
- logLines: number[];
-};
-
-const getAllEffectLabels = (
- effectsArray: ArrayExpression,
- attr: JSXAttribute,
-): {effectLabels: string[]; logLines: number[]} => {
- if (effectsArray.elements.length === 0) {
- throw new Error('Cannot delete effect: no effects found');
- }
-
- const elements = enumerateEffectArrayElements(effectsArray);
- return {
- effectLabels: elements.map((effect) =>
- effect.kind === 'call' ? `${effect.callee}()` : 'effect',
- ),
- logLines: elements.map((effect) =>
- effect.kind === 'call'
- ? (effect.node.loc?.start.line ?? attr.loc?.start.line ?? 1)
- : (attr.loc?.start.line ?? 1),
- ),
- };
-};
-
-export const deleteEffects = async ({
- input,
- effects,
- prettierConfigOverride,
-}: {
- input: string;
- effects: EffectDeletionTarget[];
- prettierConfigOverride?: Record<string, unknown> | null;
-}): Promise<{
- output: string;
- formatted: boolean;
- effectLabels: string[];
- logLines: number[];
-}> => {
- if (effects.length === 0) {
- throw new Error('No effects were specified for deletion');
- }
-
- const ast = parseAst(input);
- const deletionsByAttr = new Map<JSXAttribute, EffectsArrayDeletion>();
-
- for (const effect of effects) {
- const {sequenceNodePath} = effect;
- const jsx = findJsxElementAtNodePath(ast, sequenceNodePath);
- if (!jsx) {
- throw new Error(
- 'Could not find a JSX element at the specified location to delete effect',
- );
- }
-
- const attr = findEffectsAttr(jsx.attributes ?? []);
- if (!attr) {
- throw new Error('Could not find effects on the target JSX element');
- }
-
- const effectsArray = getEffectsArray(attr);
- const existingDeletion = deletionsByAttr.get(attr);
- const deletion =
- existingDeletion ??
- ({
- jsxAttributes: jsx.attributes,
- attr,
- effectsArray,
- allEffects: false,
- effectIndices: new Set<number>(),
- effectLabels: [],
- logLines: [],
- } satisfies EffectsArrayDeletion);
-
- deletionsByAttr.set(attr, deletion);
-
- if (effect.type === 'all-effects') {
- const {effectLabels, logLines} = getAllEffectLabels(effectsArray, attr);
- deletion.allEffects = true;
- deletion.effectIndices.clear();
- deletion.effectLabels = effectLabels;
- deletion.logLines = logLines;
- continue;
- }
-
- const {effectIndex} = effect;
- if (deletion.allEffects || deletion.effectIndices.has(effectIndex)) {
- continue;
- }
-
- const found = findEffectCallExpression({attr, effectIndex});
- if (found.kind === 'error') {
- throw new Error(`Cannot delete effect: ${found.reason}`);
- }
-
- deletion.effectIndices.add(effectIndex);
- deletion.effectLabels.push(`${found.callee}()`);
- deletion.logLines.push(
- found.call.loc?.start.line ?? jsx.loc?.start.line ?? 1,
- );
- }
-
- for (const deletion of deletionsByAttr.values()) {
- if (deletion.allEffects) {
- const attrIndex = deletion.jsxAttributes.indexOf(deletion.attr);
- if (attrIndex !== -1) {
- deletion.jsxAttributes.splice(attrIndex, 1);
- }
-
- continue;
- }
-
- for (const effectIndex of [...deletion.effectIndices].sort(
- (a, b) => b - a,
- )) {
- deletion.effectsArray.elements.splice(effectIndex, 1);
- }
-
- if (deletion.effectsArray.elements.length === 0) {
- const attrIndex = deletion.jsxAttributes.indexOf(deletion.attr);
- if (attrIndex !== -1) {
- deletion.jsxAttributes.splice(attrIndex, 1);
- }
- }
- }
-
- const finalFile = serializeAst(ast);
- const {output, formatted} = await formatFileContent({
- input: finalFile,
- prettierConfigOverride,
- });
-
- return {
- output,
- formatted,
- effectLabels: [...deletionsByAttr.values()].flatMap(
- (deletion) => deletion.effectLabels,
- ),
- logLines: [...deletionsByAttr.values()].flatMap(
- (deletion) => deletion.logLines,
- ),
- };
-};
-
-export const deleteEffect = async ({
- input,
- sequenceNodePath,
- effectIndex,
- prettierConfigOverride,
-}: {
- input: string;
- sequenceNodePath: SequenceNodePath;
- effectIndex: number;
- prettierConfigOverride?: Record<string, unknown> | null;
-}): Promise<{
- output: string;
- formatted: boolean;
- effectLabel: string;
- logLine: number;
-}> => {
- const {output, formatted, effectLabels, logLines} = await deleteEffects({
- input,
- effects: [{type: 'single-effect', sequenceNodePath, effectIndex}],
- prettierConfigOverride,
- });
-
- return {
- output,
- formatted,
- effectLabel: effectLabels[0],
- logLine: logLines[0],
- };
-};
+export {
+ deleteEffect,
+ deleteEffects,
+ type EffectDeletionTarget,
+} from '@remotion/studio-codemods';
diff --git a/packages/studio-server/src/codemods/duplicate-effect.ts b/packages/studio-server/src/codemods/duplicate-effect.ts
index 91dd22d8c3..fa2e21efc5 100644
--- a/packages/studio-server/src/codemods/duplicate-effect.ts
+++ b/packages/studio-server/src/codemods/duplicate-effect.ts
@@ -1,164 +1,5 @@
-import type {ArrayExpression, Expression, JSXAttribute} from '@babel/types';
-import {cloneNode} from '@babel/types';
-import type {SequenceNodePath} from 'remotion';
-import {findJsxElementAtNodePath} from '../preview-server/routes/can-update-sequence-props';
-import {formatFileContent} from './format-file-content';
-import {parseAst, serializeAst} from './parse-ast';
-import {
- findEffectCallExpression,
- findEffectsAttr,
-} from './update-effect-props/update-effect-props';
-
-const getEffectsArray = (attr: JSXAttribute): ArrayExpression => {
- if (!attr.value || attr.value.type !== 'JSXExpressionContainer') {
- throw new Error('Cannot duplicate effect: effects prop is not an array');
- }
-
- const expr = attr.value.expression as Expression;
- if (expr.type !== 'ArrayExpression') {
- throw new Error('Cannot duplicate effect: effects prop is not an array');
- }
-
- return expr;
-};
-
-export type EffectDuplicationTarget = {
- sequenceNodePath: SequenceNodePath;
- effectIndex: number;
-};
-
-type EffectsArrayDuplication = {
- effectsArray: ArrayExpression;
- effectIndices: Set<number>;
- effectLabels: string[];
- logLines: number[];
-};
-
-export const duplicateEffects = async ({
- input,
- effects,
- prettierConfigOverride,
-}: {
- input: string;
- effects: EffectDuplicationTarget[];
- prettierConfigOverride?: Record<string, unknown> | null;
-}): Promise<{
- output: string;
- formatted: boolean;
- effectLabels: string[];
- logLines: number[];
-}> => {
- if (effects.length === 0) {
- throw new Error('No effects were specified for duplication');
- }
-
- const ast = parseAst(input);
- const duplicationsByAttr = new Map<JSXAttribute, EffectsArrayDuplication>();
-
- for (const effect of effects) {
- const {sequenceNodePath, effectIndex} = effect;
- const jsx = findJsxElementAtNodePath(ast, sequenceNodePath);
- if (!jsx) {
- throw new Error(
- 'Could not find a JSX element at the specified location to duplicate effect',
- );
- }
-
- const attr = findEffectsAttr(jsx.attributes ?? []);
- if (!attr) {
- throw new Error('Could not find effects on the target JSX element');
- }
-
- const effectsArray = getEffectsArray(attr);
- const existingDuplication = duplicationsByAttr.get(attr);
- const duplication =
- existingDuplication ??
- ({
- effectsArray,
- effectIndices: new Set<number>(),
- effectLabels: [],
- logLines: [],
- } satisfies EffectsArrayDuplication);
-
- duplicationsByAttr.set(attr, duplication);
-
- if (duplication.effectIndices.has(effectIndex)) {
- continue;
- }
-
- const found = findEffectCallExpression({attr, effectIndex});
- if (found.kind === 'error') {
- throw new Error(`Cannot duplicate effect: ${found.reason}`);
- }
-
- duplication.effectIndices.add(effectIndex);
- duplication.effectLabels.push(`${found.callee}()`);
- duplication.logLines.push(
- found.call.loc?.start.line ?? jsx.loc?.start.line ?? 1,
- );
- }
-
- for (const duplication of duplicationsByAttr.values()) {
- for (const effectIndex of [...duplication.effectIndices].sort(
- (a, b) => b - a,
- )) {
- const effect = duplication.effectsArray.elements[effectIndex];
- if (!effect || effect.type !== 'CallExpression') {
- throw new Error('Cannot duplicate effect: not-call-expression');
- }
-
- duplication.effectsArray.elements.splice(
- effectIndex + 1,
- 0,
- cloneNode(effect, true) as never,
- );
- }
- }
-
- const finalFile = serializeAst(ast);
- const {output, formatted} = await formatFileContent({
- input: finalFile,
- prettierConfigOverride,
- });
-
- return {
- output,
- formatted,
- effectLabels: [...duplicationsByAttr.values()].flatMap(
- (duplication) => duplication.effectLabels,
- ),
- logLines: [...duplicationsByAttr.values()].flatMap(
- (duplication) => duplication.logLines,
- ),
- };
-};
-
-export const duplicateEffect = async ({
- input,
- sequenceNodePath,
- effectIndex,
- prettierConfigOverride,
-}: {
- input: string;
- sequenceNodePath: SequenceNodePath;
- effectIndex: number;
- prettierConfigOverride?: Record<string, unknown> | null;
-}): Promise<{
- output: string;
- formatted: boolean;
- effectLabel: string;
- logLine: number;
-}> => {
- const {output, formatted, effectLabels, logLines} = await duplicateEffects({
- input,
- effects: [{sequenceNodePath, effectIndex}],
- prettierConfigOverride,
- });
-
- return {
- output,
- formatted,
- effectLabel: effectLabels[0],
- logLine: logLines[0],
- };
-};
+export {
+ duplicateEffect,
+ duplicateEffects,
+ type EffectTarget as EffectDuplicationTarget,
+} from '@remotion/studio-codemods';
diff --git a/packages/studio-server/src/codemods/paste-effects.ts b/packages/studio-server/src/codemods/paste-effects.ts
index e864a1927d..a81aca431a 100644
--- a/packages/studio-server/src/codemods/paste-effects.ts
+++ b/packages/studio-server/src/codemods/paste-effects.ts
@@ -1,237 +1,8 @@
-import type {
- ArrayExpression,
- CallExpression,
- JSXAttribute,
- ObjectExpression,
- ObjectProperty,
-} from '@babel/types';
-import type {
- EffectClipboardPasteType,
- EffectClipboardSnapshot,
-} from '@remotion/studio-shared';
-import * as recast from 'recast';
-import type {SequenceNodePath} from 'remotion';
-import {getAstNodePath} from '../helpers/get-ast-node-path';
-import {findJsxElementAtNodePath} from '../preview-server/routes/can-update-sequence-props';
-import {assertValidEffect, ensureEffectImport} from './add-effect';
-import {
- ensureRemotionImportLocalNames,
- getRequiredRemotionImports,
- makeParamExpression,
- type RemotionLocalNames,
-} from './effect-param-expression';
-import {formatFileContent} from './format-file-content';
-import {parseAst, serializeAst} from './parse-ast';
-import {findEffectsAttr} from './update-effect-props/update-effect-props';
-import {
- ensureUseCurrentFrameHook,
- findEnclosingFunctionPath,
-} from './update-keyframes/ensure-imports-and-frame-hook';
+import {pasteEffects as pasteEffectsCodemod} from '@remotion/studio-codemods';
-const b = recast.types.builders;
-const identifierRegex = /^[A-Za-z_$][0-9A-Za-z_$]*$/;
-
-const getEffectsArray = (attr: JSXAttribute): ArrayExpression => {
- if (!attr.value || attr.value.type !== 'JSXExpressionContainer') {
- throw new Error('Cannot append effects: effects prop is not an array');
- }
-
- const expr = attr.value.expression;
- if (expr.type !== 'ArrayExpression') {
- throw new Error('Cannot append effects: effects prop is not an array');
- }
-
- return expr;
-};
-
-const makeEffectsAttr = (array: ArrayExpression): JSXAttribute => {
- return b.jsxAttribute(
- b.jsxIdentifier('effects'),
- b.jsxExpressionContainer(array as never),
- ) as unknown as JSXAttribute;
-};
-
-const makeEffectsArray = (calls: CallExpression[]): ArrayExpression => {
- return b.arrayExpression(calls as never) as unknown as ArrayExpression;
-};
-
-const makeParamsObjectExpression = ({
- params,
- remotionLocalNames,
-}: {
- params: EffectClipboardSnapshot['params'];
- remotionLocalNames: RemotionLocalNames;
-}): ObjectExpression => {
- return b.objectExpression(
- Object.entries(params).map(([key, param]) => {
- const keyNode = identifierRegex.test(key)
- ? b.identifier(key)
- : b.stringLiteral(key);
- return b.objectProperty(
- keyNode as never,
- makeParamExpression({param, remotionLocalNames}) as never,
- ) as ObjectProperty;
- }) as never,
- ) as ObjectExpression;
-};
-
-const makeEffectCall = ({
- ast,
- effect,
- remotionLocalNames,
-}: {
- ast: ReturnType<typeof parseAst>;
- effect: EffectClipboardSnapshot;
- remotionLocalNames: RemotionLocalNames;
-}): CallExpression => {
- assertValidEffect({
- effectName: effect.callee,
- effectImportPath: effect.importPath,
- });
- const localName = ensureEffectImport({
- ast,
- effectName: effect.callee,
- effectImportPath: effect.importPath,
- });
-
- return b.callExpression(b.identifier(localName), [
- makeParamsObjectExpression({
- params: effect.params,
- remotionLocalNames,
- }) as never,
- ]) as unknown as CallExpression;
-};
-
-const removeEffectsAttr = (
- attributes: NonNullable<
- ReturnType<typeof findJsxElementAtNodePath>
- >['attributes'],
- attr: JSXAttribute,
-) => {
- const index = attributes.indexOf(attr);
- if (index !== -1) {
- attributes.splice(index, 1);
- }
-};
-
-export const pasteEffects = async ({
- input,
- targetSequenceNodePath,
- type,
- effects,
- insertAtIndices,
- prettierConfigOverride,
-}: {
- readonly input: string;
+type PasteEffectsInput = Parameters<typeof pasteEffectsCodemod>[0] & {
readonly targetFileName: string;
- readonly targetSequenceNodePath: SequenceNodePath;
- readonly type: EffectClipboardPasteType;
- readonly effects: EffectClipboardSnapshot[];
- readonly insertAtIndices: number[] | null;
- readonly prettierConfigOverride?: Record<string, unknown> | null;
-}): Promise<{
- readonly output: string;
- readonly formatted: boolean;
- readonly effectLabels: string[];
- readonly logLine: number;
-}> => {
- const ast = parseAst(input);
- const targetJsxPath = getAstNodePath(ast, targetSequenceNodePath);
- const targetJsx = findJsxElementAtNodePath(ast, targetSequenceNodePath);
- if (!targetJsx || !targetJsxPath) {
- throw new Error(
- 'Could not find a JSX element at the specified location to paste effects',
- );
- }
-
- const requiredRemotionImports = getRequiredRemotionImports(effects);
- const remotionLocalNames = ensureRemotionImportLocalNames({
- ast,
- requiredImports: requiredRemotionImports,
- });
- if (requiredRemotionImports.has('useCurrentFrame')) {
- const fnPath = findEnclosingFunctionPath(targetJsxPath);
- if (fnPath) {
- ensureUseCurrentFrameHook(
- fnPath,
- remotionLocalNames.useCurrentFrame ?? 'useCurrentFrame',
- );
- }
- }
-
- const effectCalls = effects.map((effect) =>
- makeEffectCall({ast, effect, remotionLocalNames}),
- );
- const effectLabels = effects.map((effect) => `${effect.callee}()`);
-
- const existingAttr = findEffectsAttr(targetJsx.attributes ?? []);
-
- if (insertAtIndices !== null) {
- if (
- type !== 'effects-additive' ||
- insertAtIndices.length !== effectCalls.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) {
- removeEffectsAttr(targetJsx.attributes, existingAttr);
- }
-
- if (effectCalls.length > 0) {
- targetJsx.attributes.push(makeEffectsAttr(makeEffectsArray(effectCalls)));
- }
- } else if (effectCalls.length === 0) {
- throw new Error('Cannot paste effects: no effects were copied');
- } else if (insertAtIndices === null) {
- if (existingAttr) {
- getEffectsArray(existingAttr).elements.push(
- ...(effectCalls as ArrayExpression['elements']),
- );
- } else {
- targetJsx.attributes.push(makeEffectsAttr(makeEffectsArray(effectCalls)));
- }
- } else {
- const elements = existingAttr
- ? getEffectsArray(existingAttr).elements
- : ([] as ArrayExpression['elements']);
- const indexedCalls = effectCalls
- .map((effect, index) => ({
- effect,
- index: insertAtIndices[index] as number,
- }))
- .sort((left, right) => left.index - right.index);
- for (const indexedCall of indexedCalls) {
- elements.splice(
- Math.min(indexedCall.index, elements.length),
- 0,
- indexedCall.effect,
- );
- }
-
- if (!existingAttr) {
- targetJsx.attributes.push(
- makeEffectsAttr(
- b.arrayExpression(elements as never) as ArrayExpression,
- ),
- );
- }
- }
-
- const finalFile = serializeAst(ast);
- const {output, formatted} = await formatFileContent({
- input: finalFile,
- prettierConfigOverride,
- });
-
- return {
- output,
- formatted,
- effectLabels,
- logLine: targetJsx.loc?.start.line ?? 1,
- };
};
+
+export const pasteEffects = (input: PasteEffectsInput) =>
+ pasteEffectsCodemod(input);
diff --git a/packages/studio-server/src/codemods/reorder-effect.ts b/packages/studio-server/src/codemods/reorder-effect.ts
index d35b74adc5..9b529eb719 100644
--- a/packages/studio-server/src/codemods/reorder-effect.ts
+++ b/packages/studio-server/src/codemods/reorder-effect.ts
@@ -1,95 +1 @@
-import type {ArrayExpression, Expression, JSXAttribute} from '@babel/types';
-import type {SequenceNodePath} from 'remotion';
-import {findJsxElementAtNodePath} from '../preview-server/routes/can-update-sequence-props';
-import {formatFileContent} from './format-file-content';
-import {parseAst, serializeAst} from './parse-ast';
-import {
- enumerateEffectArrayElements,
- findEffectsAttr,
-} from './update-effect-props/update-effect-props';
-
-const getEffectsArray = (attr: JSXAttribute): ArrayExpression => {
- if (!attr.value || attr.value.type !== 'JSXExpressionContainer') {
- throw new Error('Cannot reorder effect: effects prop is not an array');
- }
-
- const expr = attr.value.expression as Expression;
- if (expr.type !== 'ArrayExpression') {
- throw new Error('Cannot reorder effect: effects prop is not an array');
- }
-
- return expr;
-};
-
-export const reorderEffect = async ({
- input,
- sequenceNodePath,
- fromIndex,
- toIndex,
- prettierConfigOverride,
-}: {
- input: string;
- sequenceNodePath: SequenceNodePath;
- fromIndex: number;
- toIndex: number;
- prettierConfigOverride?: Record<string, unknown> | null;
-}): Promise<{
- output: string;
- formatted: boolean;
- effectLabel: string;
- logLine: number;
-}> => {
- const ast = parseAst(input);
- const jsx = findJsxElementAtNodePath(ast, sequenceNodePath);
- if (!jsx) {
- throw new Error(
- 'Could not find a JSX element at the specified location to reorder effect',
- );
- }
-
- const attr = findEffectsAttr(jsx.attributes ?? []);
- if (!attr) {
- throw new Error('Could not find effects on the target JSX element');
- }
-
- const effectsArray = getEffectsArray(attr);
- const elements = enumerateEffectArrayElements(effectsArray);
- 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');
- }
-
- const target = elements[fromIndex];
- if (target.kind !== 'call') {
- throw new Error(
- 'Cannot reorder effect: source effect is not-call-expression',
- );
- }
-
- if (fromIndex !== toIndex) {
- const [moved] = effectsArray.elements.splice(fromIndex, 1);
- if (!moved) {
- throw new Error(
- 'Cannot reorder effect: source effect is not-call-expression',
- );
- }
-
- effectsArray.elements.splice(toIndex, 0, moved);
- }
-
- const finalFile = serializeAst(ast);
- const {output, formatted} = await formatFileContent({
- input: finalFile,
- prettierConfigOverride,
- });
-
- return {
- output,
- formatted,
- effectLabel: `${target.callee}()`,
- logLine: target.node.loc?.start.line ?? jsx.loc?.start.line ?? 1,
- };
-};
+export {reorderEffect} from '@remotion/studio-codemods';
diff --git a/packages/studio-server/src/codemods/update-effect-props/update-effect-props.ts b/packages/studio-server/src/codemods/update-effect-props/update-effect-props.ts
index a709dc91c3..5c7ceb3b52 100644
--- a/packages/studio-server/src/codemods/update-effect-props/update-effect-props.ts
+++ b/packages/studio-server/src/codemods/update-effect-props/update-effect-props.ts
@@ -1,474 +1,21 @@
-import type {
- ArrayExpression,
- CallExpression,
- Expression,
- File,
- JSXAttribute,
- ObjectExpression,
- ObjectProperty,
- StringLiteral,
-} from '@babel/types';
-import type {EffectClipboardParam} from '@remotion/studio-shared';
-import type {ExpressionKind} from 'ast-types/lib/gen/kinds';
-import * as recast from 'recast';
-import type {SequenceNodePath, InteractivitySchema} from 'remotion';
-import {NoReactInternals} from 'remotion/no-react';
-import {getAstNodePath} from '../../helpers/get-ast-node-path';
-import {findJsxElementAtNodePath} from '../../preview-server/routes/can-update-sequence-props';
-import {
- ensureRemotionImportLocalNames,
- getRequiredRemotionImportsForEffectParams,
- makeParamExpression,
-} from '../effect-param-expression';
-import {formatFileContent} from '../format-file-content';
-import {parseAst, serializeAst} from '../parse-ast';
-import {
- ensureUseCurrentFrameHook,
- findEnclosingFunctionPath,
-} from '../update-keyframes/ensure-imports-and-frame-hook';
-import {parseValueExpression} from '../update-nested-prop';
-
-const b = recast.types.builders;
-
-export type EffectPropUpdate =
- | {
- key: string;
- value: unknown;
- defaultValue: unknown | null;
- }
- | {
- key: string;
- effectParam: EffectClipboardParam;
- defaultValue: unknown | null;
- };
-
-export type UpdateEffectPropsResult = {
- output: string;
- formatted: boolean;
- oldValueString: string;
- newValueString: string;
- logLine: number;
- effectCallee: string;
- removedProps: PropDelta[];
-};
-
-export type PropDelta = {
- key: string;
- valueString: string;
-};
+import type {JSXAttribute} from '@babel/types';
+import {findEffectsAttr as findEffectsAttrCodemod} from '@remotion/studio-codemods';
+
+export {
+ enumerateEffectArrayElements,
+ findEffectCallExpression,
+ type EffectArrayElement,
+ type EffectPropUpdate,
+ type PropDelta,
+ type UpdateEffectPropsResult,
+ updateEffectProps,
+ updateEffectPropsAst,
+} from '@remotion/studio-codemods';
export const findEffectsAttr = (
attrs: readonly (JSXAttribute | unknown)[],
): JSXAttribute | null => {
- for (const attr of attrs) {
- if ((attr as JSXAttribute).type !== 'JSXAttribute') {
- continue;
- }
-
- const a = attr as JSXAttribute;
- if (a.name.type === 'JSXIdentifier' && a.name.name === 'effects') {
- return a;
- }
- }
-
- return null;
-};
-
-const getCalleeName = (call: CallExpression): string | null => {
- const {callee} = call;
- if (callee.type === 'Identifier') {
- return callee.name;
- }
-
- if (
- callee.type === 'MemberExpression' &&
- !callee.computed &&
- callee.property.type === 'Identifier'
- ) {
- return callee.property.name;
- }
-
- return null;
-};
-
-export type EffectArrayElement =
- | {kind: 'call'; callee: string; node: CallExpression}
- | {kind: 'unsupported'; reason: 'not-call-expression' | 'spread'};
-
-export const enumerateEffectArrayElements = (
- arr: ArrayExpression,
-): EffectArrayElement[] => {
- const out: EffectArrayElement[] = [];
- for (const el of arr.elements) {
- if (el === null) {
- out.push({kind: 'unsupported', reason: 'not-call-expression'});
- continue;
- }
-
- if (el.type === 'SpreadElement') {
- out.push({kind: 'unsupported', reason: 'spread'});
- continue;
- }
-
- if (el.type !== 'CallExpression') {
- out.push({kind: 'unsupported', reason: 'not-call-expression'});
- continue;
- }
-
- const call = el as CallExpression;
- const callee = getCalleeName(call);
- if (callee === null) {
- out.push({kind: 'unsupported', reason: 'not-call-expression'});
- continue;
- }
-
- out.push({kind: 'call', callee, node: call});
- }
-
- return out;
-};
-
-export const findEffectCallExpression = ({
- attr,
- effectIndex,
-}: {
- attr: JSXAttribute;
- effectIndex: number;
-}):
- | {kind: 'ok'; call: CallExpression; callee: string}
- | {
- kind: 'error';
- reason: 'not-found' | 'not-call-expression';
- } => {
- if (!attr.value || attr.value.type !== 'JSXExpressionContainer') {
- return {kind: 'error', reason: 'not-call-expression'};
- }
-
- const expr = attr.value.expression as Expression;
- if (expr.type !== 'ArrayExpression') {
- return {kind: 'error', reason: 'not-call-expression'};
- }
-
- const elements = enumerateEffectArrayElements(expr);
-
- if (effectIndex < 0 || effectIndex >= elements.length) {
- return {kind: 'error', reason: 'not-found'};
- }
-
- const target = elements[effectIndex];
- if (target.kind !== 'call') {
- return {kind: 'error', reason: 'not-call-expression'};
- }
-
- return {kind: 'ok', call: target.node, callee: target.callee};
-};
-
-const findObjectProperty = (
- objExpr: ObjectExpression,
- propertyName: string,
-): {propIndex: number; prop: ObjectProperty | undefined} => {
- const propIndex = objExpr.properties.findIndex(
- (p) =>
- p.type === 'ObjectProperty' &&
- ((p.key.type === 'Identifier' && p.key.name === propertyName) ||
- (p.key.type === 'StringLiteral' &&
- (p.key as StringLiteral).value === propertyName)),
+ return findEffectsAttrCodemod(
+ attrs as Parameters<typeof findEffectsAttrCodemod>[0],
);
-
- return {
- propIndex,
- prop:
- propIndex !== -1
- ? (objExpr.properties[propIndex] as ObjectProperty)
- : undefined,
- };
-};
-
-const printObjectPropertyValue = (prop: ObjectProperty) =>
- recast
- .print(prop.value)
- .code.replace(/[\n\r\t]+/g, ' ')
- .replace(/,(\s*[}\]])/g, '$1')
- .trim();
-
-const updateHasEffectParam = (
- update: EffectPropUpdate,
-): update is Extract<EffectPropUpdate, {effectParam: EffectClipboardParam}> =>
- 'effectParam' in update;
-
-const getStaticUpdateValue = (update: EffectPropUpdate): unknown | null => {
- if (updateHasEffectParam(update)) {
- return update.effectParam.type === 'static'
- ? update.effectParam.value
- : null;
- }
-
- return update.value;
-};
-
-const ensureClipboardParamImports = ({
- ast,
- sequenceNodePath,
- param,
-}: {
- ast: File;
- sequenceNodePath: SequenceNodePath;
- param: EffectClipboardParam;
-}) => {
- const requiredImports = getRequiredRemotionImportsForEffectParams([param]);
- const remotionLocalNames = ensureRemotionImportLocalNames({
- ast,
- requiredImports,
- });
-
- if (requiredImports.has('useCurrentFrame')) {
- const targetJsxPath = getAstNodePath(ast, sequenceNodePath);
- if (targetJsxPath) {
- const fnPath = findEnclosingFunctionPath(targetJsxPath);
- if (fnPath) {
- ensureUseCurrentFrameHook(
- fnPath,
- remotionLocalNames.useCurrentFrame ?? 'useCurrentFrame',
- );
- }
- }
- }
-
- return remotionLocalNames;
-};
-
-const makeUpdateValueExpression = ({
- ast,
- sequenceNodePath,
- update,
-}: {
- ast: File;
- sequenceNodePath: SequenceNodePath;
- update: EffectPropUpdate;
-}): ExpressionKind => {
- if (!updateHasEffectParam(update)) {
- return parseValueExpression(update.value);
- }
-
- const remotionLocalNames = ensureClipboardParamImports({
- ast,
- sequenceNodePath,
- param: update.effectParam,
- });
-
- return makeParamExpression({
- param: update.effectParam,
- remotionLocalNames,
- });
-};
-
-const removeObjectProperty = ({
- objExpr,
- propertyName,
-}: {
- objExpr: ObjectExpression;
- propertyName: string;
-}): PropDelta | null => {
- const {propIndex, prop} = findObjectProperty(objExpr, propertyName);
- if (!prop || propIndex === -1) {
- return null;
- }
-
- const valueString = printObjectPropertyValue(prop);
- objExpr.properties.splice(propIndex, 1);
-
- return {
- key: propertyName,
- valueString,
- };
-};
-
-export const updateEffectPropsAst = ({
- input,
- sequenceNodePath,
- effectIndex,
- update,
- schema,
-}: {
- input: string;
- sequenceNodePath: SequenceNodePath;
- effectIndex: number;
- update: EffectPropUpdate;
- schema: InteractivitySchema;
-}): {
- serialized: string;
- oldValueString: string;
- newValueString: string;
- logLine: number;
- effectCallee: string;
- removedProps: PropDelta[];
-} => {
- const ast = parseAst(input);
- const jsx = findJsxElementAtNodePath(ast, sequenceNodePath);
- if (!jsx) {
- throw new Error(
- 'Could not find a JSX element at the specified location to update effects',
- );
- }
-
- 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 {call, callee: effectCallee} = found;
-
- const isDefault =
- !updateHasEffectParam(update) &&
- update.defaultValue !== null &&
- JSON.stringify(update.value) === JSON.stringify(update.defaultValue);
-
- let objExpr: ObjectExpression;
-
- if (call.arguments.length === 0) {
- if (isDefault) {
- return {
- serialized: serializeAst(ast),
- oldValueString: '',
- newValueString: JSON.stringify(update.defaultValue),
- logLine: call.loc?.start.line ?? jsx.loc?.start.line ?? 1,
- effectCallee,
- removedProps: [],
- };
- }
-
- objExpr = b.objectExpression([]) as ObjectExpression;
- call.arguments.push(objExpr);
- } else if (call.arguments[0].type !== 'ObjectExpression') {
- throw new Error('Cannot update effect prop: computed');
- } else {
- objExpr = call.arguments[0] as ObjectExpression;
- }
-
- const {prop} = findObjectProperty(objExpr, update.key);
- const removedProps: PropDelta[] = [];
-
- let oldValueString = '';
- if (prop) {
- oldValueString = recast.print(prop.value).code;
- } else if (update.defaultValue !== null) {
- oldValueString = JSON.stringify(update.defaultValue);
- }
-
- let newValueString = '';
- if (isDefault) {
- newValueString = JSON.stringify(update.defaultValue);
- if (prop) {
- const idx = objExpr.properties.indexOf(prop);
- if (idx !== -1) {
- objExpr.properties.splice(idx, 1);
- }
- }
- } else {
- const newValueExpr = makeUpdateValueExpression({
- ast,
- sequenceNodePath,
- update,
- });
- newValueString = recast.print(newValueExpr).code;
- if (prop) {
- prop.value = newValueExpr as ObjectProperty['value'];
- } else {
- objExpr.properties.push(
- b.objectProperty(
- b.identifier(update.key),
- newValueExpr,
- ) as ObjectProperty,
- );
- }
- }
-
- const fieldSchema = schema[update.key];
- const staticUpdateValue = getStaticUpdateValue(update);
- if (
- fieldSchema &&
- fieldSchema.type === 'enum' &&
- staticUpdateValue !== null
- ) {
- const propsToDelete = NoReactInternals.findPropsToDelete({
- schema,
- key: update.key,
- value: staticUpdateValue,
- });
- for (const propToDelete of propsToDelete) {
- const removed = removeObjectProperty({
- objExpr,
- propertyName: propToDelete,
- });
- if (removed) {
- removedProps.push(removed);
- }
- }
- }
-
- const logLine = call.loc?.start.line ?? jsx.loc?.start.line ?? 1;
-
- return {
- serialized: serializeAst(ast),
- oldValueString,
- newValueString,
- logLine,
- effectCallee,
- removedProps,
- };
-};
-
-export const updateEffectProps = async ({
- input,
- sequenceNodePath,
- effectIndex,
- update,
- schema,
- prettierConfigOverride,
-}: {
- input: string;
- sequenceNodePath: SequenceNodePath;
- effectIndex: number;
- update: EffectPropUpdate;
- schema: InteractivitySchema;
- prettierConfigOverride?: Record<string, unknown> | null;
-}): Promise<UpdateEffectPropsResult> => {
- const {
- serialized,
- oldValueString,
- newValueString,
- logLine,
- effectCallee,
- removedProps,
- } = updateEffectPropsAst({
- input,
- sequenceNodePath,
- effectIndex,
- update,
- schema,
- });
-
- const {output, formatted} = await formatFileContent({
- input: serialized,
- prettierConfigOverride,
- });
-
- return {
- output,
- oldValueString,
- newValueString,
- formatted,
- logLine,
- effectCallee,
- removedProps,
- };
};
diff --git a/packages/studio-server/src/test/paste-effects.test.ts b/packages/studio-server/src/test/paste-effects.test.ts
index 3c5ec9ac2b..a2fda2a526 100644
--- a/packages/studio-server/src/test/paste-effects.test.ts
+++ b/packages/studio-server/src/test/paste-effects.test.ts
@@ -55,7 +55,7 @@ test('pasteEffects appends a copied effect to a target sequence', async () => {
});
expect(effectLabels).toEqual(['tint()']);
- expect(output).toContain('blur({radius: 5})');
+ expect(output).toMatch(/blur\(\{\s*radius: 5,?\s*\}\)/);
expect(output).toMatch(/tint\(\{\s*color: ['"]red['"],?\s*\}\)/);
});
diff --git a/packages/studio-server/src/test/update-effect-props.test.ts b/packages/studio-server/src/test/update-effect-props.test.ts
index 997d32e0b4..958e2deb0c 100644
--- a/packages/studio-server/src/test/update-effect-props.test.ts
+++ b/packages/studio-server/src/test/update-effect-props.test.ts
@@ -73,7 +73,7 @@ test('updateEffectProps adds a missing prop', () => {
expect(effectCallee).toBe('tint');
expect(serialized).toContain('opacity: 0.25');
- expect(serialized).toContain('color: "red"');
+ expect(serialized).toMatch(/color: ['"]red['"]/);
});
test('updateEffectProps writes uv-coordinate tuples', () => {
@@ -86,7 +86,7 @@ test('updateEffectProps writes uv-coordinate tuples', () => {
schema: tintSchema,
});
- expect(serialized).toContain('position: [0.25,0.75]');
+ expect(serialized).toMatch(/position: \[0\.25,\s*0\.75\]/);
});
test('updateEffectProps writes array values', () => {
@@ -103,7 +103,7 @@ test('updateEffectProps writes array values', () => {
schema: tintSchema,
});
- expect(serialized).toContain('colors: ["#ff0000","#00ff00"]');
+ expect(serialized).toMatch(/colors: \[['"]#ff0000['"],\s*['"]#00ff00['"]\]/);
});
test('updateEffectProps removes a prop equal to default', () => {
@@ -117,7 +117,7 @@ test('updateEffectProps removes a prop equal to default', () => {
});
expect(serialized).not.toContain('opacity:');
- expect(serialized).toContain('color: "red"');
+ expect(serialized).toMatch(/color: ['"]red['"]/);
});
test('updateEffectProps targets the correct effect by index when there are multiple', () => {
@@ -133,8 +133,8 @@ test('updateEffectProps targets the correct effect by index when there are multi
});
expect(serialized).toContain('opacity: 0.9');
- expect(serialized).toContain('color: "red"');
- expect(serialized).toContain('color: "green"');
+ expect(serialized).toMatch(/color: ['"]red['"]/);
+ expect(serialized).toMatch(/color: ['"]green['"]/);
});
test('updateEffectProps throws when effect index is out of range', () => {
@@ -208,7 +208,7 @@ test('updateEffectProps removes props from inactive enum variants', () => {
},
});
- expect(serialized).toContain('colorMode: "source"');
+ expect(serialized).toMatch(/colorMode: ['"]source['"]/);
expect(serialized).not.toContain('dotColor');
expect(serialized).toContain('opacity: 0.5');
expect(removedProps).toEqual([{key: 'dotColor', valueString: '"red blue"'}]);
@@ -246,13 +246,13 @@ test('updateEffectProps writes keyframed effect params from clipboard data', ()
expect(serialized).toContain('Easing');
expect(serialized).toContain('interpolate');
expect(serialized).toContain('useCurrentFrame');
- expect(serialized).toContain('from "remotion"');
+ expect(serialized).toMatch(/from ['"]remotion['"]/);
expect(serialized).toContain('const frame = useCurrentFrame();');
expect(serialized).toContain(
'opacity: interpolate(frame, [0, 30, 60], [0, 1, 0], {',
);
- expect(serialized).toContain('extrapolateLeft: "clamp"');
- expect(serialized).toContain('output: "perceptual-scale"');
+ expect(serialized).toMatch(/extrapolateLeft: ['"]clamp['"]/);
+ expect(serialized).toMatch(/output: ['"]perceptual-scale['"]/);
expect(serialized).toContain(
'easing: [Easing.bezier(0.1, 0.2, 0.3, 0.4), Easing.step1]',
);