Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Fix Element installation undo for new compositions (#11312)

Igor Samokhovets91bba18557b6
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index 61ba75eb06..3dd7c5e36a 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -2069,7 +2069,56 @@ export const createBrowserStudioOperations = ({
);
}
- const project = getProject();
+ const originalProject = getProject();
+ let project = originalProject;
+ if (request.newComposition !== null) {
+ if (request.newComposition.codemod.canvasCapture !== null) {
+ throw new Error(
+ 'Creating canvas capture compositions is not supported in Browser Studio',
+ );
+ }
+
+ if (request.newComposition.codemod.newId !== request.compositionId) {
+ throw new Error(
+ 'New composition ID does not match installation target',
+ );
+ }
+
+ const absolutePath = resolveCodemodTargetFile({
+ codemod: request.newComposition.codemod,
+ project,
+ symbolicatedStack: request.newComposition.symbolicatedStack,
+ });
+ if (absolutePath !== request.compositionFile) {
+ throw new Error(
+ 'New composition source does not match installation target',
+ );
+ }
+
+ const input = project.files[absolutePath];
+ const {newContents} = parseAndApplyCodemod({
+ input,
+ codeMod: request.newComposition.codemod,
+ });
+ const componentFilePath = `${dirname(absolutePath)}/${request.newComposition.codemod.componentName}.tsx`;
+ if (project.files[componentFilePath] !== undefined) {
+ throw new Error(
+ `Cannot create ${relativeToRoot(componentFilePath, project.rootDir)} because it already exists`,
+ );
+ }
+
+ project = {
+ ...project,
+ files: {
+ ...project.files,
+ [absolutePath]: newContents,
+ [componentFilePath]: makeNewCompositionComponentSource(
+ request.newComposition.codemod.componentName,
+ ),
+ },
+ };
+ }
+
const plan = await getElementInstallPlanForProject({
installationName: request.installationName,
destination: {
@@ -2171,7 +2220,7 @@ export const createBrowserStudioOperations = ({
dependencies: installedDependencies,
project: projectWithElement,
});
- if (getProject() !== project) {
+ if (getProject() !== originalProject) {
throw new Error(
'Project changed during Element installation. Please try again.',
);
diff --git a/packages/browser-studio/src/test/browser-studio-project-operations.test.ts b/packages/browser-studio/src/test/browser-studio-project-operations.test.ts
index 273a2b4fd4..329ba0caad 100644
--- a/packages/browser-studio/src/test/browser-studio-project-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-project-operations.test.ts
@@ -452,6 +452,7 @@ export const LowerThird = () => <Rect width={640} height={180} />;
from: 12,
overwriteExisting: false,
position: {x: 24, y: 48},
+ newComposition: null,
});
if (!inserted.success) {
throw new Error(
@@ -505,6 +506,7 @@ export const LowerThird = () => <Rect width={640} height={180} />;
from: null,
overwriteExisting: false,
position: null,
+ newComposition: null,
};
expect(await operations.insertElement(installRequest)).toMatchObject({
success: false,
@@ -558,6 +560,96 @@ export const LowerThird = () => <Rect width={640} height={180} />;
);
});
+test('installs an Element into a new composition as one undoable mutation', async () => {
+ const initialProject = createBlankTemplateProject();
+ let project = initialProject;
+ const operations = createBrowserStudioOperations({
+ dependencyVersions: {},
+ getStaticFiles: null,
+ getProject: () => project,
+ initialElement: null,
+ onProjectChange: (nextProject) => {
+ project = nextProject;
+ },
+ resolveDependencies: null,
+ });
+ const element = {
+ dependencies: [],
+ dimensions: {width: 640, height: 180},
+ displayName: 'Browser Element',
+ durationInFrames: 90,
+ initialProps: null,
+ installationMode: 'wrapped' as const,
+ slug: 'browser-element',
+ sourceCode: 'export const BrowserElement = () => <div />;\n',
+ } satisfies ElementDragData['element'];
+ const preflight = await operations.prepareElementInstall({
+ installationName: null,
+ destination: {type: 'new-composition', compositionFile: null},
+ element,
+ });
+ if (!preflight.success) {
+ throw new Error(preflight.reason);
+ }
+
+ const result = await operations.insertElement({
+ installationName: null,
+ compositionFile: preflight.plan.compositionFile,
+ compositionId: 'ElementScene',
+ element,
+ expectedFileState: preflight.plan.expectedFileState,
+ from: null,
+ overwriteExisting: false,
+ position: null,
+ newComposition: {
+ codemod: {
+ type: 'new-composition',
+ newId: 'ElementScene',
+ componentName: 'ElementScene',
+ componentImportPath: './ElementScene',
+ folderName: null,
+ parentName: null,
+ newHeight: 720,
+ newWidth: 1280,
+ newFps: 30,
+ newDurationInFrames: 90,
+ canvasCapture: null,
+ },
+ symbolicatedStack: null,
+ },
+ });
+ if (!result.success) {
+ throw new Error(
+ result.type === 'error' ? result.reason : 'Unexpected file conflict',
+ );
+ }
+
+ expect(project.files['/project/src/Root.tsx']).toContain('id="ElementScene"');
+ expect(project.files['/project/src/ElementScene.tsx']).toContain(
+ '<BrowserElement',
+ );
+ expect(project.files['/project/src/browser-element.element.tsx']).toBe(
+ element.sourceCode,
+ );
+ const installedProject = project;
+
+ expect((await operations.undo()).success).toBe(true);
+ expect(project.files['/project/src/Root.tsx']).toBe(
+ initialProject.files['/project/src/Root.tsx'],
+ );
+ expect(project.files['/project/src/ElementScene.tsx']).toBeUndefined();
+ expect(
+ project.files['/project/src/browser-element.element.tsx'],
+ ).toBeUndefined();
+ expect(await operations.undo()).toEqual({
+ success: false,
+ reason: 'Nothing to undo',
+ });
+
+ expect((await operations.redo()).success).toBe(true);
+ expect(areBrowserStudioProjectsEqual(project, installedProject)).toBe(true);
+});
+
test('installs component-owned Element timing and initial props', async () => {
let project = createBlankTemplateProject();
const operations = createBrowserStudioOperations({
@@ -610,6 +702,7 @@ test('installs component-owned Element timing and initial props', async () => {
from: 30,
overwriteExisting: false,
position: {x: 24, y: 48},
+ newComposition: null,
});
if (!inserted.success) {
throw new Error(
@@ -693,6 +786,7 @@ test('rejects contradictory component-owned Element initial props', async () =>
from: 30,
overwriteExisting: false,
position: {x: 24, y: 48},
+ newComposition: null,
});
expect(response).toMatchObject({
diff --git a/packages/example/e2e/studio-protocol.test.mts b/packages/example/e2e/studio-protocol.test.mts
index 435f9e8e22..da0ba9d0ed 100644
--- a/packages/example/e2e/studio-protocol.test.mts
+++ b/packages/example/e2e/studio-protocol.test.mts
@@ -590,6 +590,7 @@ const CloseupPlaceholder = () => {
await expect
.poll(() => fs.readFileSync(newCompositionFile, 'utf8'))
.toContain('ProtocolElement');
+ const installedComposition = fs.readFileSync(newCompositionFile, 'utf8');
expect(fs.readFileSync(newCompositionElementFile, 'utf8')).toContain(
'export const ProtocolElement',
);
@@ -628,6 +629,26 @@ const CloseupPlaceholder = () => {
.first(),
).toContainText('Protocol Element', {timeout: 30_000});
+ await studioPage.getByRole('button', {name: /^Undo/}).click();
+ await expect.poll(() => fs.existsSync(newCompositionFile)).toBe(false);
+ expect(fs.existsSync(newCompositionElementFile)).toBe(false);
+ expect(
+ fs.readFileSync(path.join(closeupDirectory, 'Closeup.tsx'), 'utf8'),
+ ).not.toContain('id="ProtocolElementScene"');
+
+ await studioPage.getByRole('button', {name: /^Redo/}).click();
+ await expect.poll(() => fs.existsSync(newCompositionFile)).toBe(true);
+ expect(fs.existsSync(newCompositionElementFile)).toBe(true);
+ expect(
+ fs.readFileSync(path.join(closeupDirectory, 'Closeup.tsx'), 'utf8'),
+ ).toBe(sourceWithNewComposition);
+ expect(fs.readFileSync(newCompositionFile, 'utf8')).toBe(
+ installedComposition,
+ );
+ expect(fs.readFileSync(newCompositionElementFile, 'utf8')).toContain(
+ 'export const ProtocolElement',
+ );
+
await studioPage.bringToFront();
await studioPage.keyboard.press('Escape');
await expect(browseElements).toBeVisible();
diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.ts
index ec87565f3f..0c5c973c6e 100644
--- a/packages/studio-server/src/helpers/resolve-composition-component.ts
+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts
@@ -18,15 +18,22 @@ import {svgMarkupToJsx} from './svg-to-jsx';
const makeCodemodEnvironment = (
remotionRoot: string,
+ sourceFileOverrides: ReadonlyMap<string, string> | null,
): InsertJsxElementCodemodEnvironment => ({
dirname: path.dirname,
extname: path.extname,
fileExists: (fileName) =>
- fs.existsSync(fileName) && fs.statSync(fileName).isFile(),
+ sourceFileOverrides?.has(path.resolve(fileName)) === true ||
+ (fs.existsSync(fileName) && fs.statSync(fileName).isFile()),
isAbsolute: path.isAbsolute,
join: path.join,
pathSeparator: path.sep,
- readFile: (fileName) => fs.promises.readFile(fileName, 'utf-8'),
+ readFile: (fileName) => {
+ const override = sourceFileOverrides?.get(path.resolve(fileName));
+ return override === undefined
+ ? fs.promises.readFile(fileName, 'utf-8')
+ : Promise.resolve(override);
+ },
relative: path.relative,
resolve: path.resolve,
rootDir: remotionRoot,
@@ -50,7 +57,7 @@ export const resolveCompositionComponentWithFile = ({
resolveCompositionComponentWithFileCodemod({
compositionFile,
compositionId,
- environment: makeCodemodEnvironment(remotionRoot),
+ environment: makeCodemodEnvironment(remotionRoot, null),
});
export const resolveCompositionComponent = ({
@@ -65,7 +72,7 @@ export const resolveCompositionComponent = ({
resolveCompositionComponentCodemod({
compositionFile,
compositionId,
- environment: makeCodemodEnvironment(remotionRoot),
+ environment: makeCodemodEnvironment(remotionRoot, null),
});
export const insertJsxElementIntoComposition = ({
@@ -76,6 +83,7 @@ export const insertJsxElementIntoComposition = ({
from,
prettierConfigOverride,
wrapInSequence = null,
+ sourceFileOverrides,
}: {
remotionRoot: string;
compositionFile: string;
@@ -90,6 +98,7 @@ export const insertJsxElementIntoComposition = ({
name: string | null;
position: InsertableCompositionElementPosition | null;
} | null;
+ sourceFileOverrides: ReadonlyMap<string, string> | null;
}): Promise<{
fileName: string;
source: string;
@@ -103,7 +112,7 @@ export const insertJsxElementIntoComposition = ({
compositionFile,
compositionId,
element,
- environment: makeCodemodEnvironment(remotionRoot),
+ environment: makeCodemodEnvironment(remotionRoot, sourceFileOverrides),
from,
prettierConfigOverride,
wrapInSequence:
diff --git a/packages/studio-server/src/preview-server/routes/apply-codemod.ts b/packages/studio-server/src/preview-server/routes/apply-codemod.ts
index 345268ac9c..8b6663dbad 100644
--- a/packages/studio-server/src/preview-server/routes/apply-codemod.ts
+++ b/packages/studio-server/src/preview-server/routes/apply-codemod.ts
@@ -27,7 +27,7 @@ import {
withSourceFileWriteQueue,
} from './source-file-write-queue';
-const formatNewCompositionFile = (
+export const formatNewCompositionFile = (
codemod: Extract<ApplyCodemodRequest['codemod'], {type: 'new-composition'}>,
) => {
if (codemod.canvasCapture !== null) {
diff --git a/packages/studio-server/src/preview-server/routes/insert-element.ts b/packages/studio-server/src/preview-server/routes/insert-element.ts
index 8de07ac07f..a1f8a17e52 100644
--- a/packages/studio-server/src/preview-server/routes/insert-element.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-element.ts
@@ -1,19 +1,28 @@
+import {existsSync, readFileSync} from 'node:fs';
+import path from 'node:path';
import {RenderInternals} from '@remotion/renderer';
import type {
ElementInstallExpectedFileState,
InsertElementRequest,
InsertElementResponse,
} from '@remotion/studio-shared';
+import {
+ applyCodemodToFile,
+ resolveFilePathFromSymbolicatedStack,
+} from '../../codemods/apply-codemod-to-file';
import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import {insertJsxElementIntoComposition} from '../../helpers/resolve-composition-component';
import type {ApiHandler} from '../api-types';
import {formatLogFileLocation} from '../format-log-file-location';
+import {getProjectInfo} from '../project-info';
import {broadcastSequenceNodePathMutation} from '../sequence-node-path-mutation';
import {
printUndoHint,
pushTransactionToUndoStack,
suppressUndoStackInvalidation,
} from '../undo-stack';
+import {formatNewCompositionFile} from './apply-codemod';
+import {checkIfTypeScriptFile} from './can-update-default-props';
import {
getElementInstallPlan,
validateElementInstallPosition,
@@ -58,6 +67,7 @@ export const insertElementHandler: ApiHandler<
from,
position,
overwriteExisting,
+ newComposition,
},
entryPoint,
remotionRoot,
@@ -108,13 +118,92 @@ export const insertElementHandler: ApiHandler<
`[insert-element] Received request for compositionFile="${compositionFile}" compositionId="${compositionId}" element="${element.slug}"`,
);
+ let compositionCreation: {
+ componentFilePath: string;
+ componentFileContents: string;
+ registrationFilePath: string;
+ registrationFileOldContents: string;
+ registrationFileNewContents: string;
+ } | null = null;
+ let sourceFileOverrides: ReadonlyMap<string, string> | null = null;
+
+ if (newComposition !== null) {
+ if (newComposition.codemod.newId !== compositionId) {
+ throw new Error(
+ 'New composition ID does not match installation target',
+ );
+ }
+
+ const registrationFilePath = newComposition.symbolicatedStack
+ ? resolveFilePathFromSymbolicatedStack(
+ remotionRoot,
+ newComposition.symbolicatedStack,
+ )
+ : (await getProjectInfo(remotionRoot, entryPoint)).rootFile;
+ if (registrationFilePath === null) {
+ throw new Error('Cannot find file for composition in project');
+ }
+
+ checkIfTypeScriptFile(registrationFilePath);
+ if (
+ path.resolve(remotionRoot, compositionFile) !== registrationFilePath
+ ) {
+ throw new Error(
+ 'New composition source does not match installation target',
+ );
+ }
+
+ const componentFilePath = path.join(
+ path.dirname(registrationFilePath),
+ `${newComposition.codemod.componentName}.tsx`,
+ );
+ if (existsSync(componentFilePath)) {
+ throw new Error(
+ `Cannot create ${path.relative(
+ remotionRoot,
+ componentFilePath,
+ )} because it already exists`,
+ );
+ }
+
+ const registrationFileOldContents = readFileSync(
+ registrationFilePath,
+ 'utf-8',
+ );
+ const registrationFileNewContents = await applyCodemodToFile({
+ filePath: registrationFilePath,
+ codeMod: newComposition.codemod,
+ });
+ const componentFileContents = await formatNewCompositionFile(
+ newComposition.codemod,
+ );
+ compositionCreation = {
+ componentFileContents,
+ componentFilePath,
+ registrationFileNewContents,
+ registrationFileOldContents,
+ registrationFilePath,
+ };
+ sourceFileOverrides = new Map([
+ [registrationFilePath, registrationFileNewContents],
+ [componentFilePath, componentFileContents],
+ ]);
+ }
+
+ const installDestination =
+ newComposition === null
+ ? {
+ type: 'current-composition' as const,
+ compositionFile,
+ compositionId,
+ }
+ : {
+ type: 'new-composition' as const,
+ compositionFile,
+ };
const plan = await getElementInstallPlan({
installationName,
- destination: {
- type: 'current-composition',
- compositionFile,
- compositionId,
- },
+ destination: installDestination,
element,
entryPoint,
remotionRoot,
@@ -158,14 +247,27 @@ export const insertElementHandler: ApiHandler<
};
}
+ if (
+ compositionCreation !== null &&
+ plan.elementFileName ===
+ path.join(
+ path.dirname(plan.safePaths.compositionFileName),
+ path.basename(compositionCreation.componentFilePath),
+ )
+ ) {
+ throw new Error(
+ 'Element source file conflicts with the new composition file',
+ );
+ }
+
const shouldWriteElementFile =
!plan.elementFileExists || elementSourcesDiffer;
- const inserted = await insertJsxElementIntoComposition({
+ const insertionInput = {
remotionRoot,
compositionFile,
compositionId,
element: {
- type: 'component',
+ type: 'component' as const,
componentName: plan.componentName,
importName: plan.componentName,
importPath: plan.importPath,
@@ -198,14 +300,23 @@ export const insertElementHandler: ApiHandler<
name: element.displayName,
position,
},
+ };
+ const inserted = await insertJsxElementIntoComposition({
+ ...insertionInput,
+ sourceFileOverrides,
});
+ if (
+ compositionCreation !== null &&
+ inserted.fileName !== compositionCreation.componentFilePath
+ ) {
+ throw new Error(
+ 'New composition component does not match installation target',
+ );
+ }
+
const finalPlan = await getElementInstallPlan({
installationName,
- destination: {
- type: 'current-composition',
- compositionFile,
- compositionId,
- },
+ destination: installDestination,
element,
entryPoint,
remotionRoot,
@@ -228,6 +339,17 @@ export const insertElementHandler: ApiHandler<
throw new Error('Element source changed during installation');
}
+ if (
+ compositionCreation !== null &&
+ (readFileSync(compositionCreation.registrationFilePath, 'utf-8') !==
+ compositionCreation.registrationFileOldContents ||
+ existsSync(compositionCreation.componentFilePath))
+ ) {
+ throw new Error(
+ 'Composition source changed during Element installation',
+ );
+ }
+
const nodePathMutation = broadcastSequenceNodePathMutation(
[
{
@@ -240,6 +362,18 @@ export const insertElementHandler: ApiHandler<
pushTransactionToUndoStack({
snapshots: [
+ ...(compositionCreation === null
+ ? []
+ : [
+ {
+ filePath: compositionCreation.registrationFilePath,
+ oldContents: compositionCreation.registrationFileOldContents,
+ newContents: compositionCreation.registrationFileNewContents,
+ logLine:
+ newComposition?.symbolicatedStack?.originalLineNumber ?? 1,
+ nodePathRemappings: null,
+ },
+ ]),
...(shouldWriteElementFile
? [
{
@@ -253,7 +387,8 @@ export const insertElementHandler: ApiHandler<
: []),
{
filePath: inserted.fileName,
- oldContents: inserted.oldContents,
+ oldContents:
+ compositionCreation === null ? inserted.oldContents : null,
newContents: inserted.output,
logLine: inserted.logLine,
nodePathRemappings: inserted.nodePathRemappings,
@@ -261,19 +396,38 @@ export const insertElementHandler: ApiHandler<
],
logLevel,
remotionRoot,
- description: {
- undoMessage: `↩️ Added ${element.displayName}`,
- redoMessage: `↪️ Added ${element.displayName}`,
- },
+ description:
+ newComposition === null
+ ? {
+ undoMessage: `↩️ Added ${element.displayName}`,
+ redoMessage: `↪️ Added ${element.displayName}`,
+ }
+ : {
+ undoMessage: `↩️ Installation of ${element.displayName} into composition "${compositionId}"`,
+ redoMessage: `↪️ Installation of ${element.displayName} into composition "${compositionId}"`,
+ },
entryType: 'insert-jsx-element',
suppressHmrOnFileRestore: false,
});
+ if (compositionCreation !== null) {
+ suppressUndoStackInvalidation(compositionCreation.registrationFilePath);
+ }
+
if (shouldWriteElementFile) {
suppressUndoStackInvalidation(plan.elementFileName);
}
suppressUndoStackInvalidation(inserted.fileName);
+ if (compositionCreation !== null) {
+ writeFileAndNotifyFileWatchers({
+ file: compositionCreation.registrationFilePath,
+ content: compositionCreation.registrationFileNewContents,
+ originatorClientId: undefined,
+ metadata: null,
+ });
+ }
+
if (shouldWriteElementFile) {
writeFileAndNotifyFileWatchers({
file: plan.elementFileName,
@@ -290,6 +444,19 @@ export const insertElementHandler: ApiHandler<
metadata: {skipSequencePropsUpdate: true},
});
+ if (newComposition !== null && compositionCreation !== null) {
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(
+ formatLogFileLocation({
+ remotionRoot,
+ absolutePath: compositionCreation.registrationFilePath,
+ line: newComposition.symbolicatedStack?.originalLineNumber ?? 1,
+ }),
+ )} Created composition "${compositionId}"`,
+ );
+ }
+
const compositionLocationLabel = formatLogFileLocation({
remotionRoot,
absolutePath: inserted.fileName,
diff --git a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts b/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
index 040a795527..82c69ba51f 100644
--- a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
@@ -257,6 +257,7 @@ export const insertJsxElementHandler: ApiHandler<
element,
from,
prettierConfigOverride: null,
+ sourceFileOverrides: null,
});
const nodePathMutation = broadcastSequenceNodePathMutation(
[
diff --git a/packages/studio-server/src/test/insert-element.test.ts b/packages/studio-server/src/test/insert-element.test.ts
index 72c80c9175..17c863a3e7 100644
--- a/packages/studio-server/src/test/insert-element.test.ts
+++ b/packages/studio-server/src/test/insert-element.test.ts
@@ -152,6 +152,7 @@ const makeFixture = () => {
from: null,
overwriteExisting,
position: null,
+ newComposition: null,
});
};
@@ -280,6 +281,69 @@ test('plans a new-composition install without resolving the selected component',
}
});
+test('invalidates a new-composition install after an external component edit', async () => {
+ const fixture = makeFixture();
+ try {
+ const response = await fixture.callHandlerWithInput({
+ installationName: null,
+ compositionFile: 'Root.tsx',
+ compositionId: 'ElementScene',
+ element,
+ expectedFileState: {exists: false},
+ from: null,
+ overwriteExisting: false,
+ position: null,
+ newComposition: {
+ codemod: {
+ type: 'new-composition',
+ newId: 'ElementScene',
+ componentName: 'ElementScene',
+ componentImportPath: './ElementScene',
+ folderName: null,
+ parentName: null,
+ newHeight: 720,
+ newWidth: 1280,
+ newFps: 30,
+ newDurationInFrames: 90,
+ canvasCapture: null,
+ },
+ symbolicatedStack: {
+ originalFunctionName: null,
+ originalFileName: 'Root.tsx',
+ originalLineNumber: 6,
+ originalColumnNumber: 1,
+ originalScriptCode: null,
+ },
+ },
+ });
+ if (!response.success) {
+ throw new Error(
+ response.type === 'error'
+ ? response.reason
+ : 'Unexpected file conflict',
+ );
+ }
+
+ const componentFile = path.join(
+ path.dirname(fixture.compositionFile),
+ 'ElementScene.tsx',
+ );
+ expect(getUndoStack()).toHaveLength(1);
+ writeFileSync(
+ componentFile,
+ `${readFileSync(componentFile, 'utf-8')}\n// External edit\n`,
+ );
+ const startedAt = Date.now();
+ while (getUndoStack().length > 0 && Date.now() - startedAt < 2000) {
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+
+ expect(getUndoStack()).toHaveLength(0);
+ } finally {
+ fixture.cleanup();
+ }
+});
+
test('creates a new Element file without an overwrite conflict', async () => {
const fixture = makeFixture();
try {
@@ -333,6 +397,7 @@ test('installs structured initial props on a component-owned Sequence', async ()
from: 30,
overwriteExisting: false,
position: {x: 120, y: 80},
+ newComposition: null,
});
if (!response.success) {
@@ -389,6 +454,7 @@ test('rejects contradictory component-owned installation props', async () => {
from: 30,
overwriteExisting: false,
position: {x: 120, y: 80},
+ newComposition: null,
});
expect(response).toMatchObject({success: false, type: 'error'});
expect(readFileSync(fixture.compositionFile, 'utf-8')).toBe(
@@ -416,6 +482,7 @@ test('keeps wrapped installation and passes initial props to its child', async (
from: 12,
overwriteExisting: false,
position: {x: 40, y: 50},
+ newComposition: null,
});
if (!response.success) {
throw new Error(
@@ -453,6 +520,7 @@ test('materializes independent props for two component-owned copies', async () =
from: 0,
overwriteExisting: false,
position: null,
+ newComposition: null,
});
expect(first.success).toBe(true);
const second = await fixture.callHandlerWithInput({
@@ -464,6 +532,7 @@ test('materializes independent props for two component-owned copies', async () =
from: 30,
overwriteExisting: false,
position: null,
+ newComposition: null,
});
expect(second.success).toBe(true);
@@ -505,6 +574,7 @@ test('installs independent named copies into the same and another composition',
from: null,
position: null,
overwriteExisting: false,
+ newComposition: null,
};
expect((await fixture.callHandlerWithInput(input)).success).toBe(true);
const secondComposition = readFileSync(fixture.compositionFile, 'utf-8');
@@ -633,6 +703,7 @@ test.each(['../outside', 'nested/name', 'Uppercase', '', 'name.element.tsx'])(
from: null,
position: null,
overwriteExisting: false,
+ newComposition: null,
}),
).toMatchObject({success: false, type: 'error'});
expect(readFileSync(fixture.compositionFile, 'utf-8')).toBe(
diff --git a/packages/studio-server/src/test/resolve-composition-component.test.ts b/packages/studio-server/src/test/resolve-composition-component.test.ts
index eef8fea338..882d04e9b4 100644
--- a/packages/studio-server/src/test/resolve-composition-component.test.ts
+++ b/packages/studio-server/src/test/resolve-composition-component.test.ts
@@ -459,6 +459,7 @@ test('inserts a Solid next to a self-closing root without wrapping it', async ()
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.output).toContain(
@@ -531,6 +532,7 @@ test('inserts an asset as a sibling of a connected composition', async () => {
},
from: 42,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
const connectedCompositionEnd = result.output.indexOf('</Sequence>');
@@ -587,6 +589,7 @@ test('inserts beside a parenthesized self-closing root without wrapping it', asy
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
const videoStart = result.output.indexOf('<Video');
@@ -788,6 +791,7 @@ test('inserts a Solid into the resolved composition component', async () => {
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.source).toBe('MyComp.tsx');
@@ -845,6 +849,7 @@ test('inserts a Solid with a translate style', async () => {
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.output).toContain("position: 'absolute'");
@@ -895,6 +900,7 @@ test('rounds the translate style to one decimal place', async () => {
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.output).toContain("position: 'absolute'");
@@ -944,6 +950,7 @@ test('inserts an aliased Solid import if Solid is already defined', async () =>
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.output).toContain(
@@ -989,6 +996,7 @@ test('inserts a Solid into an empty component returning null', async () => {
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.output).toContain("import { Solid } from 'remotion';");
@@ -1021,6 +1029,7 @@ test('inserts a Solid into an empty component returning null', async () => {
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(secondInsert.output.match(/<Solid/g)?.length).toBe(2);
} finally {
@@ -1066,6 +1075,7 @@ test('converts and inserts SVG markup as an Interactive.Svg', async () => {
},
from: 42,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.output).toContain(
@@ -1132,6 +1142,7 @@ test('inserts a CanvasImage asset at a timeline frame', async () => {
},
from: 42,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.output).toContain(
@@ -1198,6 +1209,7 @@ test('inserts a CanvasImage asset with a translate style', async () => {
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.output).toContain(
@@ -1255,6 +1267,7 @@ test('inserts an AnimatedImage asset into the resolved composition component', a
},
from: 42,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.output).toContain(
@@ -1318,6 +1331,7 @@ test('inserts a Video asset with its duration and CSS dimensions', async () => {
},
from: 42,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.output).toContain("import {Video} from '@remotion/media';");
@@ -1381,6 +1395,7 @@ test('rejects inserting a Video asset if Video is already defined', async () =>
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
}),
).rejects.toThrow('Cannot add <Video> because Video is already defined');
} finally {
@@ -1432,6 +1447,7 @@ test('inserts a Gif asset into the resolved composition component', async () =>
},
from: 42,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.output).toContain("import {Gif} from '@remotion/gif';");
@@ -1493,6 +1509,7 @@ test('inserts an Audio asset into the resolved composition component', async ()
},
from: 42,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.output).toContain("import {Audio} from '@remotion/media';");
@@ -1551,6 +1568,7 @@ test('inserts a remote audio asset with a literal URL', async () => {
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.output).toContain("import {Audio} from '@remotion/media';");
@@ -1609,6 +1627,7 @@ test('rejects inserting an Audio asset if Audio is already defined', async () =>
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
}),
).rejects.toThrow('Cannot add <Audio> because Audio is already defined');
} finally {
@@ -1660,6 +1679,7 @@ test('inserts a component into the resolved composition component', async () =>
},
from: 42,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.output).toContain("import {Circle} from '@remotion/shapes';");
@@ -1721,6 +1741,7 @@ test('adds value imports without reusing or colliding with type-only component i
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(aliasedResult.output).toContain('LowerThird as LowerThird2');
expect(aliasedResult.output).toContain('<LowerThird2');
@@ -1753,6 +1774,7 @@ test('adds value imports without reusing or colliding with type-only component i
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.output).toContain(
"import {LowerThird} from './lower-third.element';",
@@ -1803,6 +1825,7 @@ test('wraps a component in a dimensionless Sequence', async () => {
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
wrapInSequence: {
dimensions: null,
from: 42,
@@ -1892,6 +1915,7 @@ test('inserts a composition as a duration-aware Sequence', async () => {
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.output).toContain("import {Source} from './Source';");
@@ -2065,6 +2089,7 @@ test('inserts a default-exported composition next to an existing namespace impor
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
});
expect(result.output).toContain(
@@ -2141,6 +2166,7 @@ test('rejects array payloads for resolved composition props', async () => {
},
from: null,
prettierConfigOverride: {singleQuote: true, useTabs: true},
+ sourceFileOverrides: null,
}),
).rejects.toThrow('Resolved composition props must be an object');
} finally {
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index ebc2c75d42..cd2157158b 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -1046,6 +1046,10 @@ export type InsertElementRequest = {
from: number | null;
position: InsertableCompositionElementPosition | null;
overwriteExisting: boolean;
+ newComposition: {
+ codemod: Extract<RecastCodemod, {type: 'new-composition'}>;
+ symbolicatedStack: SymbolicatedStackFrame | null;
+ } | null;
};
export type InsertElementFileConflict = {
diff --git a/packages/studio/src/components/ElementInstallConfirmation.tsx b/packages/studio/src/components/ElementInstallConfirmation.tsx
index 7d7d00368c..ba5f80fc95 100644
--- a/packages/studio/src/components/ElementInstallConfirmation.tsx
+++ b/packages/studio/src/components/ElementInstallConfirmation.tsx
@@ -34,6 +34,7 @@ import {useZIndex} from '../state/z-index';
import {Button} from './Button';
import {prepareElementInstall} from './element-install-api';
import {insertElement} from './import-assets';
+import {useSelectComposition} from './InitialCompositionLoader';
import {Flex, Row, Spacing} from './layout';
import {LazySyntaxHighlightedSource} from './LazySyntaxHighlightedSource';
import {
@@ -54,7 +55,6 @@ import {
ValidationMessage,
WarningTriangle,
} from './NewComposition/ValidationMessage';
-import {showNotification} from './Notifications/NotificationCenter';
import {RadioButton} from './RadioButton';
import {SegmentedControl} from './SegmentedControl';
import {
@@ -375,6 +375,7 @@ export const ElementInstallConfirmation: React.FC<{
const {canvasContent, compositions} = useContext(
Internals.CompositionManager,
);
+ const selectComposition = useSelectComposition();
const currentCompositionMetadata =
config === null ||
canvasContent?.type !== 'composition' ||
@@ -519,8 +520,8 @@ export const ElementInstallConfirmation: React.FC<{
}, [folderCompositionFile, newPlan, request.element, selectedFolderStack]);
const {
+ codemod: newCompositionCodemod,
compositionId: newCompositionId,
- createComposition,
heightValidationMessage,
nameValidationMessage,
valid: newCompositionValuesAreValid,
@@ -605,12 +606,6 @@ export const ElementInstallConfirmation: React.FC<{
const activePlan = overwriteExisting
? existingDestination.plan
: (preparedInstallation?.plan ?? null);
- const [createdComposition, setCreatedComposition] = useState<string | null>(
- null,
- );
- const creationKey = JSON.stringify(newCompositionValues);
- const compositionAlreadyCreated = createdComposition === creationKey;
-
useEffect(() => {
if (selectedPlan === null) {
return;
@@ -714,7 +709,7 @@ export const ElementInstallConfirmation: React.FC<{
: requestedName !== null))) &&
(mode === 'current-composition'
? currentPlan !== null
- : (newCompositionValuesAreValid || compositionAlreadyCreated) &&
+ : newCompositionValuesAreValid &&
folderTargetIsReady &&
selectedNewCompositionPlan !== null);
@@ -724,24 +719,6 @@ export const ElementInstallConfirmation: React.FC<{
}
setSubmitting(true);
- if (mode === 'new-composition' && !compositionAlreadyCreated) {
- const created = await createComposition({
- signal: new AbortController().signal,
- symbolicatedStack:
- selectedFolderStack === null ? null : folderSymbolicatedStack,
- });
- if (!created.success) {
- showNotification(
- `Could not create composition: ${created.reason}`,
- 4000,
- );
- setSubmitting(false);
- return;
- }
-
- setCreatedComposition(creationKey);
- }
-
const installed = await insertElement({
installationName: overwriteExisting
? (existingDestination?.name ?? installationName)
@@ -758,28 +735,49 @@ export const ElementInstallConfirmation: React.FC<{
from: mode === 'new-composition' ? null : request.from,
overwriteExisting,
position: mode === 'new-composition' ? null : request.position,
+ newComposition:
+ mode === 'new-composition'
+ ? {
+ codemod: newCompositionCodemod,
+ symbolicatedStack:
+ selectedFolderStack === null ? null : folderSymbolicatedStack,
+ }
+ : null,
});
- if (installed) onClose();
- else {
+ if (installed) {
+ if (mode === 'new-composition') {
+ selectComposition(
+ {
+ id: newCompositionId,
+ folderName: newCompositionValues.folder.folderName,
+ parentFolderName: newCompositionValues.folder.parentName,
+ },
+ true,
+ );
+ }
+
+ onClose();
+ } else {
setSubmitting(false);
setRefreshPlan((value) => value + 1);
}
}, [
activePlan,
existingDestination,
- compositionAlreadyCreated,
- creationKey,
installationName,
overwriteExisting,
canSubmit,
- createComposition,
folderSymbolicatedStack,
mode,
+ newCompositionCodemod,
newCompositionId,
onClose,
request,
selectedFolderStack,
selectedPlan,
+ selectComposition,
+ newCompositionValues.folder.folderName,
+ newCompositionValues.folder.parentName,
]);
const cancel = useCallback(() => {
@@ -882,9 +880,7 @@ export const ElementInstallConfirmation: React.FC<{
compositionId={newCompositionId}
heightValidationMessage={heightValidationMessage}
inputRef={inputRef}
- nameValidationMessage={
- compositionAlreadyCreated ? null : nameValidationMessage
- }
+ nameValidationMessage={nameValidationMessage}
setValues={setNewCompositionValues}
values={newCompositionValues}
widthValidationMessage={widthValidationMessage}
diff --git a/packages/studio/src/components/import-assets.ts b/packages/studio/src/components/import-assets.ts
index 998ae9e4bd..c0bf4946bc 100644
--- a/packages/studio/src/components/import-assets.ts
+++ b/packages/studio/src/components/import-assets.ts
@@ -9,6 +9,7 @@ import {
type FileType,
type InsertableCompositionElement,
type InsertableCompositionElementPosition,
+ type InsertElementRequest,
type InstallableElement,
} from '@remotion/studio-shared';
import {Internals, staticFile} from 'remotion';
@@ -1327,6 +1328,7 @@ export const insertElement = async ({
position,
from,
overwriteExisting,
+ newComposition,
}: {
installationName: string | null;
compositionFile: string;
@@ -1336,6 +1338,7 @@ export const insertElement = async ({
position: InsertableCompositionElementPosition | null;
from: number | null;
overwriteExisting: boolean;
+ newComposition: InsertElementRequest['newComposition'];
}) => {
try {
if (getBrowserStudioOperations() === null) {
@@ -1351,6 +1354,7 @@ export const insertElement = async ({
from,
overwriteExisting,
position,
+ newComposition,
});
if (!response.success) {