Skip to content

🎥 Make videos programmatically with React

Elements: Create independent copies on reinstall by default

Igor Samokhovets5b3efd4e7c12
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index e261a8c810..621a4e876e 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -187,9 +187,6 @@ const makeSequencePropsSubscriptionKey = ({
effectKeys,
});
-const normalizeElementSource = (source: string) =>
- source.replace(/\r\n/g, '\n').trim();
-
const getElementSourceHash = async (source: string) => {
const hash = await crypto.subtle.digest(
'SHA-256',
@@ -320,6 +317,7 @@ export const ${componentName}: React.FC = () => {
const getElementInstallPlanForProject = async ({
destination,
element,
+ installationName,
project,
}: Parameters<BrowserStudioOperations['prepareElementInstall']>[0] & {
project: VirtualProject;
@@ -329,9 +327,19 @@ const getElementInstallPlanForProject = async ({
element.sourceCode,
);
const elementFileName = StudioProtocolInternals.makeElementFileNameFromSlug(
- element.slug,
+ installationName ?? element.slug,
);
- if (componentName === null || elementFileName === null) {
+ if (
+ elementFileName === null ||
+ (typeof installationName === 'string' &&
+ elementFileName !== `${installationName}.element.tsx`)
+ ) {
+ throw new Error(
+ 'Use a lowercase installation name with letters, numbers and hyphens, without a file extension.',
+ );
+ }
+
+ if (componentName === null) {
throw new Error('Invalid Element source');
}
@@ -2008,6 +2016,7 @@ export const createBrowserStudioOperations = ({
try {
const project = getProject();
const plan = await getElementInstallPlanForProject({
+ installationName: request.installationName,
destination: {
type: 'current-composition',
compositionFile: request.compositionFile,
@@ -2038,15 +2047,7 @@ export const createBrowserStudioOperations = ({
throw new Error('Element source changed during installation');
}
- const sourcesDiffer =
- plan.existingSource !== null &&
- normalizeElementSource(plan.existingSource) !==
- normalizeElementSource(request.element.sourceCode);
- if (
- sourcesDiffer &&
- !request.overwriteExisting &&
- plan.existingSource !== null
- ) {
+ if (!request.overwriteExisting && plan.existingSource !== null) {
return {
success: false,
type: 'file-conflict',
@@ -2115,6 +2116,12 @@ export const createBrowserStudioOperations = ({
dependencies: installedDependencies,
project: projectWithElement,
});
+ if (getProject() !== project) {
+ throw new Error(
+ 'Project changed during Element installation. Please try again.',
+ );
+ }
+
const nodePathMutation = controller.applyMutation({
fileName: insertion.filePath,
mutate: () => nextProject,
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 83467c67e4..0a9150b98e 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
@@ -408,6 +408,7 @@ export const LowerThird = () => <Rect width={640} height={180} />;
`,
} satisfies ElementDragData['element'];
const preflight = await operations.prepareElementInstall({
+ installationName: null,
destination: {
type: 'current-composition',
compositionFile: '/project/src/Composition.tsx',
@@ -425,6 +426,7 @@ export const LowerThird = () => <Rect width={640} height={180} />;
filePath: 'src/lower-third.element.tsx',
});
const newCompositionPreflight = await operations.prepareElementInstall({
+ installationName: null,
destination: {
type: 'new-composition',
compositionFile: null,
@@ -441,6 +443,7 @@ export const LowerThird = () => <Rect width={640} height={180} />;
});
const inserted = await operations.insertElement({
+ installationName: null,
compositionFile: '/project/src/Composition.tsx',
compositionId: 'MyComp',
element,
@@ -488,6 +491,67 @@ export const LowerThird = () => <Rect width={640} height={180} />;
expect(project.files['/project/src/lower-third.element.tsx']).toBe(
element.sourceCode,
);
+
+ const installRequest = {
+ installationName: null,
+ compositionFile: '/project/src/Composition.tsx',
+ compositionId: 'MyComp',
+ element,
+ expectedFileState: null,
+ from: null,
+ overwriteExisting: false,
+ position: null,
+ };
+ expect(await operations.insertElement(installRequest)).toMatchObject({
+ success: false,
+ type: 'file-conflict',
+ });
+ const customizedSource = `${element.sourceCode}\n// Customized\n`;
+ project = {
+ ...project,
+ files: {
+ ...project.files,
+ '/project/src/lower-third.element.tsx': customizedSource,
+ },
+ };
+ expect(
+ (
+ await operations.insertElement({
+ ...installRequest,
+ installationName: 'speaker-name',
+ })
+ ).success,
+ ).toBe(true);
+ expect(project.files['/project/src/speaker-name.element.tsx']).toBe(
+ element.sourceCode,
+ );
+ expect(project.files['/project/src/lower-third.element.tsx']).toBe(
+ customizedSource,
+ );
+ expect(project.files['/project/src/Composition.tsx']).toContain(
+ 'LowerThird as LowerThird2',
+ );
+ expect(project.files['/project/src/Composition.tsx']).toContain(
+ '<LowerThird2',
+ );
+ expect(
+ (
+ await operations.insertElement({
+ ...installRequest,
+ overwriteExisting: true,
+ })
+ ).success,
+ ).toBe(true);
+ expect(project.files['/project/src/lower-third.element.tsx']).toBe(
+ element.sourceCode,
+ );
+ expect((await operations.undo()).success).toBe(true);
+ expect(project.files['/project/src/lower-third.element.tsx']).toBe(
+ customizedSource,
+ );
+ expect(project.files['/project/src/speaker-name.element.tsx']).toBe(
+ element.sourceCode,
+ );
});
test('installs packages as an undoable project mutation and reports structured failures', async () => {
diff --git a/packages/example/e2e/studio-protocol.test.mts b/packages/example/e2e/studio-protocol.test.mts
index ab1d2a5262..441b54f2ec 100644
--- a/packages/example/e2e/studio-protocol.test.mts
+++ b/packages/example/e2e/studio-protocol.test.mts
@@ -371,6 +371,7 @@ const CloseupPlaceholder = () => {
await newDestination.press('ArrowLeft');
await expect(currentDestination).toBeChecked();
await expect(dialog.getByText(senderUrl, {exact: true})).toBeVisible();
+ await expect(dialog.getByLabel('Installation name')).toBeHidden();
await expect(
decoyStudioPage.getByText('Install Protocol Element', {exact: true}),
).toHaveCount(0);
@@ -405,6 +406,17 @@ const CloseupPlaceholder = () => {
/<Sequence\b(?=[^>]*\bfrom=\{45\})(?=[^>]*\bdurationInFrames=\{30\})[^>]*>\s*<ProtocolElement\s*\/>\s*<\/Sequence>/,
);
+ const suppliedSource = fs.readFileSync(elementFile, 'utf8');
+ const customizedSource = `${suppliedSource}\n// My customizations\n`;
+ fs.writeFileSync(elementFile, customizedSource);
+ const existingCopies = [
+ 'protocol-element-copy',
+ 'protocol-element-copy-2',
+ ].map((name) => path.join(temporaryProject, 'src', `${name}.element.tsx`));
+ for (const file of existingCopies) {
+ fs.writeFileSync(file, customizedSource);
+ }
+
await studioPage.bringToFront();
await studioPage.mouse.click(500, 300);
const senderPage = await context.newPage();
@@ -415,6 +427,119 @@ const CloseupPlaceholder = () => {
name: 'Install Protocol Element',
});
await expect(newCompositionDialog).toBeVisible();
+ await expect(
+ newCompositionDialog.getByRole('radio', {name: 'Create a copy'}),
+ ).toBeChecked();
+ await expect(newCompositionDialog.getByPlaceholder('New name')).toHaveValue(
+ 'protocol-element-copy-3',
+ );
+ await newCompositionDialog.screenshot({
+ path: test.info().outputPath('install-copy-desktop.png'),
+ });
+ const desktopViewport = studioPage.viewportSize();
+ await studioPage.setViewportSize({width: 390, height: 844});
+ await expect(
+ newCompositionDialog.getByPlaceholder('New name'),
+ ).toBeVisible();
+ expect(
+ await newCompositionDialog.evaluate(
+ (node) => node.scrollWidth <= node.clientWidth,
+ ),
+ ).toBe(true);
+ await newCompositionDialog.screenshot({
+ path: test.info().outputPath('install-copy-mobile.png'),
+ });
+ if (desktopViewport) await studioPage.setViewportSize(desktopViewport);
+ await expect(
+ newCompositionDialog.getByRole('button', {name: /^Install/}),
+ ).toBeEnabled();
+ await newCompositionDialog
+ .getByLabel('Installation name')
+ .fill('protocol-element-copy');
+ await expect(
+ newCompositionDialog.getByText('Name already taken.'),
+ ).toBeVisible();
+ await expect(
+ newCompositionDialog.getByLabel('Installation name'),
+ ).toHaveValue('protocol-element-copy');
+ await expect(
+ newCompositionDialog.getByRole('button', {name: /^Install/}),
+ ).toBeDisabled();
+ await newCompositionDialog
+ .getByLabel('Installation name')
+ .fill('speaker-name');
+ await expect(
+ newCompositionDialog.getByRole('button', {name: /^Install/}),
+ ).toBeEnabled();
+ await newCompositionDialog
+ .getByRole('radio', {name: 'Replace existing'})
+ .check();
+ await expect(
+ newCompositionDialog.getByLabel('Installation name'),
+ ).toBeHidden();
+ await expect(
+ newCompositionDialog.getByRole('button', {name: /Replace and insert/}),
+ ).toBeEnabled();
+ await newCompositionDialog
+ .getByRole('radio', {name: 'Create a copy', exact: true})
+ .check();
+ await expect(
+ newCompositionDialog.getByLabel('Installation name'),
+ ).toHaveValue('speaker-name');
+ await newCompositionDialog.getByRole('button', {name: /^Install/}).click();
+ await expect(newCompositionDialog).toBeHidden();
+ const independentFile = path.join(
+ temporaryProject,
+ 'src',
+ 'speaker-name.element.tsx',
+ );
+ await waitForFile(independentFile);
+ expect(fs.readFileSync(independentFile, 'utf8')).toBe(suppliedSource);
+ expect(fs.readFileSync(elementFile, 'utf8')).toBe(customizedSource);
+ for (const file of existingCopies) {
+ expect(fs.readFileSync(file, 'utf8')).toBe(customizedSource);
+ }
+ expect(
+ fs.readFileSync(
+ path.join(temporaryProject, 'src', 'Composition.tsx'),
+ 'utf8',
+ ),
+ ).toContain('ProtocolElement as ProtocolElement2');
+
+ await senderPage.getByRole('button', {name: 'Install in Studio'}).click();
+ await expect(newCompositionDialog).toBeVisible();
+ await newCompositionDialog
+ .getByRole('radio', {name: 'Replace existing'})
+ .check();
+ await expect(
+ newCompositionDialog.getByText(
+ 'Overwrites customizations for all usages.',
+ ),
+ ).toBeVisible();
+ await expect(
+ newCompositionDialog.getByLabel('Installation name'),
+ ).toBeHidden();
+ const changedSinceConfirmation = `${customizedSource}// Another edit\n`;
+ fs.writeFileSync(elementFile, changedSinceConfirmation);
+ await newCompositionDialog
+ .getByRole('button', {name: /Replace and insert/})
+ .click();
+ await expect(
+ newCompositionDialog.getByRole('radio', {name: 'Create a copy'}),
+ ).toBeChecked();
+ expect(fs.readFileSync(elementFile, 'utf8')).toBe(changedSinceConfirmation);
+ await newCompositionDialog
+ .getByRole('radio', {name: 'Replace existing'})
+ .check();
+ await newCompositionDialog
+ .getByRole('button', {name: /Replace and insert/})
+ .click();
+ await expect(newCompositionDialog).toBeHidden();
+ expect(fs.readFileSync(elementFile, 'utf8')).toBe(suppliedSource);
+ expect(fs.readFileSync(independentFile, 'utf8')).toBe(suppliedSource);
+
+ await senderPage.getByRole('button', {name: 'Install in Studio'}).click();
+ await expect(newCompositionDialog).toBeVisible();
await newCompositionDialog
.getByRole('radio', {name: 'New composition'})
.click();
diff --git a/packages/studio-codemods/src/insert-jsx-element.ts b/packages/studio-codemods/src/insert-jsx-element.ts
index 2c9ee9af8a..833c791ef0 100644
--- a/packages/studio-codemods/src/insert-jsx-element.ts
+++ b/packages/studio-codemods/src/insert-jsx-element.ts
@@ -1661,17 +1661,17 @@ const ensureComponentImport = ({
return existingLocalName;
}
- if (hasTopLevelBinding({ast, name: componentName})) {
- throw new Error(
- `Cannot add <${componentName}> because ${componentName} is already defined`,
- );
+ let localName = componentName;
+ let suffix = 2;
+ while (hasTopLevelBinding({ast, name: localName})) {
+ localName = `${componentName}${suffix++}`;
}
return ensureNamedImport({
ast,
importedName: importName,
sourcePath: importPath,
- localName: componentName,
+ localName,
});
};
diff --git a/packages/studio-server/src/preview-server/routes/element-install-plan.ts b/packages/studio-server/src/preview-server/routes/element-install-plan.ts
index b7e50d5538..43eea0ac90 100644
--- a/packages/studio-server/src/preview-server/routes/element-install-plan.ts
+++ b/packages/studio-server/src/preview-server/routes/element-install-plan.ts
@@ -11,10 +11,6 @@ import {resolveCompositionComponentWithFile} from '../../helpers/resolve-composi
import {getProjectInfo} from '../project-info';
import {getSafeElementInstallPaths} from './safe-element-install-path';
-export const normalizeElementSourceForComparison = (source: string) => {
- return source.replace(/\r\n/g, '\n').trim();
-};
-
export const getElementSourceHash = (source: string) => {
return createHash('sha256').update(source).digest('hex');
};
@@ -114,6 +110,7 @@ const getExpectedFileState = (
export const getElementInstallPlan = async ({
destination,
element,
+ installationName,
entryPoint,
remotionRoot,
}: PrepareElementInstallRequest & {
@@ -143,10 +140,16 @@ export const getElementInstallPlan = async ({
}
const derivedElementFileName =
- StudioProtocolInternals.makeElementFileNameFromSlug(element.slug);
- if (derivedElementFileName === null) {
+ StudioProtocolInternals.makeElementFileNameFromSlug(
+ installationName ?? element.slug,
+ );
+ if (
+ derivedElementFileName === null ||
+ (typeof installationName === 'string' &&
+ derivedElementFileName !== `${installationName}.element.tsx`)
+ ) {
throw new Error(
- 'Element slug must produce a safe lowercase .tsx file name',
+ 'Use a lowercase installation name with letters, numbers and hyphens, without a file extension.',
);
}
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 981dc4ac84..de0a82f720 100644
--- a/packages/studio-server/src/preview-server/routes/insert-element.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-element.ts
@@ -16,7 +16,6 @@ import {
} from '../undo-stack';
import {
getElementInstallPlan,
- normalizeElementSourceForComparison,
validateElementInstallPosition,
} from './element-install-plan';
import {
@@ -54,6 +53,7 @@ export const insertElementHandler: ApiHandler<
compositionFile,
compositionId,
element,
+ installationName,
expectedFileState,
from,
position,
@@ -86,6 +86,7 @@ export const insertElementHandler: ApiHandler<
);
const plan = await getElementInstallPlan({
+ installationName,
destination: {
type: 'current-composition',
compositionFile,
@@ -120,14 +121,9 @@ export const insertElementHandler: ApiHandler<
const elementSourcesDiffer =
plan.existingElementSource !== null &&
- normalizeElementSourceForComparison(plan.existingElementSource) !==
- normalizeElementSourceForComparison(element.sourceCode);
+ plan.existingElementSource !== element.sourceCode;
- if (
- elementSourcesDiffer &&
- !overwriteExisting &&
- plan.existingElementSource !== null
- ) {
+ if (!overwriteExisting && plan.existingElementSource !== null) {
return {
success: false,
type: 'file-conflict',
@@ -178,6 +174,7 @@ export const insertElementHandler: ApiHandler<
},
});
const finalPlan = await getElementInstallPlan({
+ installationName,
destination: {
type: 'current-composition',
compositionFile,
diff --git a/packages/studio-server/src/test/insert-element.test.ts b/packages/studio-server/src/test/insert-element.test.ts
index 8ac0c98243..0ed8ddc317 100644
--- a/packages/studio-server/src/test/insert-element.test.ts
+++ b/packages/studio-server/src/test/insert-element.test.ts
@@ -26,6 +26,7 @@ import {
clearUndoStackForTests,
getUndoStack,
popUndo,
+ popRedo,
} from '../preview-server/undo-stack';
const compositionSource = `import React from 'react';
@@ -123,6 +124,7 @@ const makeFixture = () => {
expectedFileState: InsertElementRequest['expectedFileState'] = null,
) => {
return callHandlerWithInput({
+ installationName: null,
compositionFile: 'Root.tsx',
compositionId: 'target',
element,
@@ -142,6 +144,7 @@ const makeFixture = () => {
destination: PrepareElementInstallRequest['destination'],
) => {
const input: PrepareElementInstallRequest = {
+ installationName: null,
destination,
element,
};
@@ -298,6 +301,7 @@ test('installs an Element with a component-owned Sequence', async () => {
const fixture = makeFixture();
try {
const response = await fixture.callHandlerWithInput({
+ installationName: null,
compositionFile: 'Root.tsx',
compositionId: 'target',
element: {...element, installationMode: 'component-owned-sequence'},
@@ -324,18 +328,76 @@ test('installs an Element with a component-owned Sequence', async () => {
}
});
-test('reuses an identical Element file without an overwrite conflict', async () => {
+test('installs independent named copies into the same and another composition', async () => {
const fixture = makeFixture();
try {
- writeFileSync(fixture.elementFile, incomingElementSource);
- const response = await fixture.callHandler(false);
+ expect((await fixture.callHandler(false)).success).toBe(true);
+ // Even identical source must not be implicitly reused.
+ expect(await fixture.callHandler(false)).toMatchObject({
+ success: false,
+ type: 'file-conflict',
+ });
+ writeFileSync(fixture.elementFile, existingElementSource);
+ const firstComposition = readFileSync(fixture.compositionFile, 'utf-8');
+ const root = path.dirname(fixture.compositionFile);
+ const secondFile = path.join(root, 'speaker-name.element.tsx');
+ const thirdFile = path.join(root, 'guest-name.element.tsx');
+ const otherComposition = path.join(root, 'Interview.tsx');
+ writeFileSync(
+ otherComposition,
+ compositionSource.replace('id="target"', 'id="interview"'),
+ );
- expect(response.success).toBe(true);
- expect(readFileSync(fixture.elementFile, 'utf-8')).toBe(
- incomingElementSource,
+ const input: InsertElementRequest = {
+ installationName: 'speaker-name',
+ compositionFile: 'Root.tsx',
+ compositionId: 'target',
+ element,
+ expectedFileState: {exists: false},
+ from: null,
+ position: null,
+ overwriteExisting: false,
+ };
+ expect((await fixture.callHandlerWithInput(input)).success).toBe(true);
+ const secondComposition = readFileSync(fixture.compositionFile, 'utf-8');
+ expect(secondComposition).toContain('LowerThird as LowerThird2');
+ expect(secondComposition).toContain('./speaker-name.element');
+ expect(secondComposition).toContain('<LowerThird2');
+ expect(secondComposition).toContain('<LowerThird ');
+ expect(readFileSync(secondFile, 'utf-8')).toBe(incomingElementSource);
+
+ expect(popUndo().success).toBe(true);
+ expect(existsSync(secondFile)).toBe(false);
+ expect(readFileSync(fixture.compositionFile, 'utf-8')).toBe(
+ firstComposition,
);
- expect(readFileSync(fixture.compositionFile, 'utf-8')).toContain(
- '<LowerThird',
+ expect(popRedo().success).toBe(true);
+ expect(readFileSync(secondFile, 'utf-8')).toBe(incomingElementSource);
+ expect(readFileSync(fixture.compositionFile, 'utf-8')).toBe(
+ secondComposition,
+ );
+
+ expect(
+ (
+ await fixture.callHandlerWithInput({
+ ...input,
+ installationName: 'guest-name',
+ compositionFile: 'Interview.tsx',
+ compositionId: 'interview',
+ })
+ ).success,
+ ).toBe(true);
+ expect(readFileSync(otherComposition, 'utf-8')).toContain(
+ './guest-name.element',
+ );
+ expect(readFileSync(thirdFile, 'utf-8')).toBe(incomingElementSource);
+ writeFileSync(
+ secondFile,
+ 'export const LowerThird = () => <div>Speaker</div>;',
+ );
+ expect(readFileSync(thirdFile, 'utf-8')).toBe(incomingElementSource);
+ expect(readFileSync(fixture.elementFile, 'utf-8')).toBe(
+ existingElementSource,
);
} finally {
fixture.cleanup();
@@ -369,39 +431,72 @@ test('returns a structured conflict without changing the project', async () => {
}
});
-test('does not overwrite a file that changed after planning', async () => {
- const fixture = makeFixture();
- try {
- const planned = await fixture.prepareInstall(fixture.currentDestination);
- if (!planned.success) {
- throw new Error(planned.reason);
- }
+test.each([null, incomingElementSource])(
+ 'does not overwrite a file that changed after planning (previous source: %s)',
+ async (previousSource) => {
+ const fixture = makeFixture();
+ try {
+ if (previousSource !== null)
+ writeFileSync(fixture.elementFile, previousSource);
+ const planned = await fixture.prepareInstall(fixture.currentDestination);
+ if (!planned.success) {
+ throw new Error(planned.reason);
+ }
- writeFileSync(fixture.elementFile, existingElementSource);
- const response = await fixture.callHandler(
- true,
- planned.plan.expectedFileState,
- );
+ writeFileSync(fixture.elementFile, existingElementSource);
+ const response = await fixture.callHandler(
+ true,
+ planned.plan.expectedFileState,
+ );
- expect(response).toEqual({
- success: false,
- type: 'file-conflict',
- conflict: {
- filePath: 'lower-third.element.tsx',
- existingSource: existingElementSource,
- incomingSource: incomingElementSource,
- },
- });
- expect(readFileSync(fixture.elementFile, 'utf-8')).toBe(
- existingElementSource,
- );
- expect(readFileSync(fixture.compositionFile, 'utf-8')).toBe(
- compositionSource,
- );
- } finally {
- fixture.cleanup();
- }
-});
+ expect(response).toEqual({
+ success: false,
+ type: 'file-conflict',
+ conflict: {
+ filePath: 'lower-third.element.tsx',
+ existingSource: existingElementSource,
+ incomingSource: incomingElementSource,
+ },
+ });
+ expect(readFileSync(fixture.elementFile, 'utf-8')).toBe(
+ existingElementSource,
+ );
+ expect(readFileSync(fixture.compositionFile, 'utf-8')).toBe(
+ compositionSource,
+ );
+ } finally {
+ fixture.cleanup();
+ }
+ },
+);
+
+test.each(['../outside', 'nested/name', 'Uppercase', '', 'name.element.tsx'])(
+ 'rejects unsafe installation name %s without changing the project',
+ async (installationName) => {
+ const fixture = makeFixture();
+ try {
+ expect(
+ await fixture.callHandlerWithInput({
+ installationName,
+ compositionFile: 'Root.tsx',
+ compositionId: 'target',
+ element,
+ expectedFileState: null,
+ from: null,
+ position: null,
+ overwriteExisting: false,
+ }),
+ ).toMatchObject({success: false, type: 'error'});
+ expect(readFileSync(fixture.compositionFile, 'utf-8')).toBe(
+ compositionSource,
+ );
+ expect(existsSync(fixture.elementFile)).toBe(false);
+ expect(getUndoStack()).toHaveLength(0);
+ } finally {
+ fixture.cleanup();
+ }
+ },
+);
test('rejects an Element source symlink that escapes the project', async () => {
const fixture = makeFixture();
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 347f9c96c7..eef8fea338 100644
--- a/packages/studio-server/src/test/resolve-composition-component.test.ts
+++ b/packages/studio-server/src/test/resolve-composition-component.test.ts
@@ -1675,7 +1675,7 @@ test('inserts a component into the resolved composition component', async () =>
}
});
-test('rejects type-only component imports instead of using them as values', async () => {
+test('adds value imports without reusing or colliding with type-only component imports', async () => {
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'remotion-resolve-'));
try {
await fs.writeFile(
@@ -1707,25 +1707,24 @@ test('rejects type-only component imports instead of using them as values', asyn
].join('\n'),
);
- await expect(
- insertJsxElementIntoComposition({
- remotionRoot: tempDir,
- compositionFile: 'Root.tsx',
- compositionId: 'test',
- element: {
- type: 'component',
- componentName: 'LowerThird',
- importName: 'LowerThird',
- importPath: './lower-third.element',
- props: [],
- position: null,
- },
- from: null,
- prettierConfigOverride: {singleQuote: true, useTabs: true},
- }),
- ).rejects.toThrow(
- 'Cannot add <LowerThird> because LowerThird is already defined',
- );
+ const aliasedResult = await insertJsxElementIntoComposition({
+ remotionRoot: tempDir,
+ compositionFile: 'Root.tsx',
+ compositionId: 'test',
+ element: {
+ type: 'component',
+ componentName: 'LowerThird',
+ importName: 'LowerThird',
+ importPath: './lower-third.element',
+ props: [],
+ position: null,
+ },
+ from: null,
+ prettierConfigOverride: {singleQuote: true, useTabs: true},
+ });
+ expect(aliasedResult.output).toContain('LowerThird as LowerThird2');
+ expect(aliasedResult.output).toContain('<LowerThird2');
+ expect(aliasedResult.output).toMatch(/\btype\s+(?:\{\s*)?LowerThird\b/);
}
await fs.writeFile(
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 7e20264396..472f2fae69 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -1008,6 +1008,7 @@ export type ElementInstallDestination =
};
export type PrepareElementInstallRequest = {
+ installationName: string | null;
destination: ElementInstallDestination;
element: InstallableElement;
};
@@ -1028,6 +1029,7 @@ export type PrepareElementInstallResponse =
};
export type InsertElementRequest = {
+ installationName: string | null;
compositionFile: string;
compositionId: string;
element: InstallableElement;
diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsx
index fa2215cc32..7f43aeb9b2 100644
--- a/packages/studio/src/components/Canvas.tsx
+++ b/packages/studio/src/components/Canvas.tsx
@@ -1021,6 +1021,7 @@ export const Canvas: React.FC<{
try {
const [newPreflight, currentPreflight] = await Promise.all([
prepareElementInstall({
+ installationName: null,
destination: {
type: 'new-composition',
compositionFile: null,
@@ -1028,6 +1029,7 @@ export const Canvas: React.FC<{
element: activeElementInstallRequest.element,
}),
prepareElementInstall({
+ installationName: null,
destination: {
type: 'current-composition',
compositionFile: activeElementInstallRequest.compositionFile,
diff --git a/packages/studio/src/components/ConfigureLicenseModal.tsx b/packages/studio/src/components/ConfigureLicenseModal.tsx
index f415419dc2..6e7a19fb29 100644
--- a/packages/studio/src/components/ConfigureLicenseModal.tsx
+++ b/packages/studio/src/components/ConfigureLicenseModal.tsx
@@ -231,6 +231,7 @@ export const LicenseSettings: React.FC = () => {
<div aria-label="License type" role="radiogroup">
<RadioButton
checked={licenseType === 'free'}
+ disabled={false}
onClick={toggleFreeLicense}
>
I am eligible for the Free License
@@ -240,6 +241,7 @@ export const LicenseSettings: React.FC = () => {
) : null}
<RadioButton
checked={licenseType === 'company'}
+ disabled={false}
onClick={toggleCompanyLicense}
>
I need a Company License
diff --git a/packages/studio/src/components/ElementInstallConfirmation.tsx b/packages/studio/src/components/ElementInstallConfirmation.tsx
index 0acca579fe..62250655ec 100644
--- a/packages/studio/src/components/ElementInstallConfirmation.tsx
+++ b/packages/studio/src/components/ElementInstallConfirmation.tsx
@@ -45,11 +45,13 @@ import {
NewCompositionFields,
type NewCompositionFormValues,
} from './NewComposition/NewComposition';
+import {RemotionInput} from './NewComposition/RemInput';
import {
ValidationMessage,
WarningTriangle,
} from './NewComposition/ValidationMessage';
import {showNotification} from './Notifications/NotificationCenter';
+import {RadioButton} from './RadioButton';
import {
hasResolvedStack,
useResolvedStack,
@@ -356,6 +358,13 @@ export const ElementLibraryAddConfirmation: React.FC<{
);
};
+type PreparedElementInstallation = {
+ basePlan: ElementInstallPlan;
+ name: string;
+ refresh: number;
+ plan: ElementInstallPlan & {filePath: string};
+};
+
type NewCompositionPlanState =
| {
readonly type: 'loading';
@@ -493,6 +502,7 @@ export const ElementInstallConfirmation: React.FC<{
type: 'loading',
});
prepareElementInstall({
+ installationName: null,
destination: {
type: 'new-composition',
compositionFile: folderCompositionFile,
@@ -559,30 +569,145 @@ export const ElementInstallConfirmation: React.FC<{
: null;
const selectedPlan =
mode === 'current-composition' ? currentPlan : selectedNewCompositionPlan;
+ const elementBaseName = request.element.slug.split('/').at(-1) ?? '';
+ const [installationName, setInstallationName] = useState(elementBaseName);
+ const [nameEdited, setNameEdited] = useState(false);
+ const [refreshPlan, setRefreshPlan] = useState(0);
+ const [preparedInstallation, setPreparedInstallation] =
+ useState<PreparedElementInstallation | null>(null);
+ const [existingInstallation, setExistingInstallation] =
+ useState<PreparedElementInstallation | null>(null);
+ const existingDestination =
+ existingInstallation?.basePlan === selectedPlan &&
+ existingInstallation?.refresh === refreshPlan
+ ? existingInstallation
+ : null;
+ const [planError, setPlanError] = useState<string | null>(null);
+ const [overwritePlan, setOverwritePlan] = useState<ElementInstallPlan | null>(
+ null,
+ );
+ const overwriteExisting =
+ existingDestination !== null && overwritePlan === existingDestination.plan;
+ const activePlan = overwriteExisting
+ ? existingDestination.plan
+ : preparedInstallation?.basePlan === selectedPlan &&
+ preparedInstallation?.name === installationName &&
+ preparedInstallation?.refresh === refreshPlan
+ ? preparedInstallation.plan
+ : null;
+ const [createdComposition, setCreatedComposition] = useState<string | null>(
+ null,
+ );
+ const creationKey = JSON.stringify(newCompositionValues);
+ const compositionAlreadyCreated = createdComposition === creationKey;
+
+ useEffect(() => {
+ setInstallationName(elementBaseName);
+ setNameEdited(false);
+ }, [elementBaseName, selectedPlan]);
+
+ useEffect(() => {
+ setOverwritePlan(null);
+ setPlanError(null);
+ if (selectedPlan === null) {
+ return;
+ }
+
+ let canceled = false;
+ prepareElementInstall({
+ installationName,
+ destination:
+ mode === 'current-composition'
+ ? {
+ type: 'current-composition',
+ compositionFile: request.compositionFile,
+ compositionId: request.compositionId,
+ }
+ : {
+ type: 'new-composition',
+ compositionFile: selectedPlan.compositionFile,
+ },
+ element: request.element,
+ })
+ .then((result) => {
+ if (canceled) return;
+ if (result.success) {
+ const prepared = {
+ basePlan: selectedPlan,
+ name: installationName,
+ refresh: refreshPlan,
+ plan: result.plan,
+ };
+ setPreparedInstallation(prepared);
+ if (result.plan.expectedFileState.exists) {
+ setExistingInstallation((previous) =>
+ previous?.basePlan === selectedPlan &&
+ previous.refresh === refreshPlan
+ ? previous
+ : prepared,
+ );
+ if (!nameEdited) {
+ let nextName = `${elementBaseName}-copy`;
+ if (installationName !== elementBaseName) {
+ const nextNumber =
+ installationName === nextName
+ ? 2
+ : Number(installationName.slice(nextName.length + 1)) + 1;
+ nextName += `-${nextNumber}`;
+ }
+
+ setInstallationName(nextName);
+ }
+ }
+ } else {
+ setPlanError(result.reason);
+ }
+ })
+ .catch((error) => {
+ if (!canceled)
+ setPlanError(error instanceof Error ? error.message : String(error));
+ });
+ return () => {
+ canceled = true;
+ };
+ }, [
+ elementBaseName,
+ nameEdited,
+ installationName,
+ mode,
+ refreshPlan,
+ request,
+ selectedPlan,
+ ]);
+
+ const installationNameError =
+ installationName.length > 0
+ ? (planError ??
+ (nameEdited && activePlan?.expectedFileState.exists
+ ? 'Name already taken.'
+ : null))
+ : null;
const folderTargetIsReady =
selectedFolderStack === null ||
(hasResolvedStack(selectedFolderStack) && folderCompositionFile !== null);
const title = `Install ${request.element.displayName}${request.element.displayName.endsWith(' Element') ? '' : ' Element'}`;
const canSubmit =
!submitting &&
+ activePlan !== null &&
+ (!activePlan.expectedFileState.exists || overwriteExisting) &&
(mode === 'current-composition'
? currentPlan !== null
- : newCompositionValuesAreValid &&
+ : (newCompositionValuesAreValid || compositionAlreadyCreated) &&
folderTargetIsReady &&
selectedNewCompositionPlan !== null);
const submit = useCallback(async () => {
- if (!canSubmit) {
+ if (!canSubmit || activePlan === null) {
return;
}
setSubmitting(true);
- if (mode === 'new-composition') {
- if (selectedNewCompositionPlan === null) {
- setSubmitting(false);
- return;
- }
-
+ if (mode === 'new-composition' && !compositionAlreadyCreated) {
const created = await createComposition({
signal: new AbortController().signal,
symbolicatedStack:
@@ -597,45 +722,52 @@ export const ElementInstallConfirmation: React.FC<{
return;
}
- await insertElement({
- compositionFile: selectedNewCompositionPlan.compositionFile,
- compositionId: newCompositionValues.id,
- element: request.element,
- expectedFileState: selectedNewCompositionPlan.expectedFileState,
- from: null,
- overwriteExisting: selectedNewCompositionPlan.expectedFileState.exists,
- position: null,
- });
- onClose();
- return;
- }
-
- if (currentPlan === null) {
- setSubmitting(false);
- return;
+ setCreatedComposition(creationKey);
}
- await insertElement({
- compositionFile: request.compositionFile,
- compositionId: request.compositionId,
+ const installed = await insertElement({
+ installationName: overwriteExisting
+ ? (existingDestination?.name ?? installationName)
+ : installationName,
+ compositionFile:
+ mode === 'new-composition'
+ ? activePlan.compositionFile
+ : request.compositionFile,
+ compositionId:
+ mode === 'new-composition'
+ ? newCompositionValues.id
+ : request.compositionId,
element: request.element,
- expectedFileState: currentPlan.expectedFileState,
- from: request.from,
- overwriteExisting: currentPlan.expectedFileState.exists,
- position: request.position,
+ expectedFileState: activePlan.expectedFileState,
+ from: mode === 'new-composition' ? null : request.from,
+ overwriteExisting,
+ position: mode === 'new-composition' ? null : request.position,
});
- onClose();
+ if (installed) onClose();
+ else {
+ if (overwriteExisting && existingDestination !== null) {
+ setInstallationName(existingDestination.name);
+ setNameEdited(false);
+ }
+
+ setSubmitting(false);
+ setRefreshPlan((value) => value + 1);
+ }
}, [
+ activePlan,
+ existingDestination,
+ compositionAlreadyCreated,
+ creationKey,
+ installationName,
+ overwriteExisting,
canSubmit,
createComposition,
- currentPlan,
folderSymbolicatedStack,
mode,
newCompositionValues.id,
onClose,
request,
selectedFolderStack,
- selectedNewCompositionPlan,
]);
const cancel = useCallback(() => {
@@ -769,7 +901,9 @@ export const ElementInstallConfirmation: React.FC<{
<NewCompositionFields
heightValidationMessage={heightValidationMessage}
inputRef={inputRef}
- nameValidationMessage={nameValidationMessage}
+ nameValidationMessage={
+ compositionAlreadyCreated ? null : nameValidationMessage
+ }
setValues={setNewCompositionValues}
values={newCompositionValues}
widthValidationMessage={widthValidationMessage}
@@ -784,11 +918,86 @@ export const ElementInstallConfirmation: React.FC<{
</section>
) : null}
- {selectedPlan?.expectedFileState.exists ? (
- <p style={overwriteStyle} role="status">
- This will replace the existing Element source file.
- </p>
- ) : null}
+ <section style={sectionStyle} aria-label="Element implementation">
+ {existingDestination ? (
+ <div
+ role="radiogroup"
+ aria-label="Existing Element file"
+ style={sectionStyle}
+ >
+ <RadioButton
+ checked={!overwriteExisting}
+ disabled={submitting}
+ onClick={() => setOverwritePlan(null)}
+ >
+ Create a copy
+ </RadioButton>
+ {!overwriteExisting ? (
+ <div
+ style={{
+ ...sectionStyle,
+ paddingLeft: 28,
+ maxWidth: 320,
+ minWidth: 0,
+ }}
+ >
+ <RemotionInput
+ rightAlign={false}
+ status={installationNameError ? 'error' : 'ok'}
+ id="element-install-name"
+ name="installationName"
+ aria-label="Installation name"
+ placeholder="New name"
+ value={installationName}
+ disabled={submitting}
+ onChange={(event) => {
+ setNameEdited(true);
+ setInstallationName(event.target.value);
+ }}
+ />
+ {installationNameError ? (
+ <ValidationMessage
+ align="flex-start"
+ message={installationNameError}
+ type="error"
+ />
+ ) : null}
+ </div>
+ ) : null}
+ <div style={sectionStyle}>
+ <RadioButton
+ checked={overwriteExisting}
+ disabled={submitting}
+ onClick={() => setOverwritePlan(existingDestination.plan)}
+ >
+ Replace existing
+ </RadioButton>
+ <p
+ style={{
+ ...warningDescriptionStyle,
+ paddingLeft: 28,
+ overflowWrap: 'anywhere',
+ }}
+ >
+ {existingDestination.plan.filePath}
+ </p>
+ {overwriteExisting ? (
+ <p style={{...overwriteStyle, paddingLeft: 28}}>
+ Overwrites customizations for all usages.
+ </p>
+ ) : null}
+ </div>
+ </div>
+ ) : activePlan ? (
+ <p style={metadataDescriptionStyle}>{activePlan.filePath}</p>
+ ) : planError ? (
+ <ValidationMessage
+ align="flex-start"
+ message={planError}
+ type="error"
+ />
+ ) : null}
+ </section>
{missingPackages.length > 0 ? (
<section
@@ -840,7 +1049,11 @@ export const ElementInstallConfirmation: React.FC<{
disabled={!canSubmit}
onClick={submit}
>
- {submitting ? 'Installing…' : 'Install'}
+ {submitting
+ ? 'Installing…'
+ : overwriteExisting
+ ? 'Replace and insert'
+ : 'Install'}
<ShortcutHint keyToPress="↵" cmdOrCtrl={false} />
</ModalButton>
</Row>
diff --git a/packages/studio/src/components/RadioButton.tsx b/packages/studio/src/components/RadioButton.tsx
index 8836c6e5ca..7e2db95091 100644
--- a/packages/studio/src/components/RadioButton.tsx
+++ b/packages/studio/src/components/RadioButton.tsx
@@ -68,12 +68,14 @@ const label: React.CSSProperties = {
export const RadioButton: React.FC<{
readonly checked: boolean;
+ readonly disabled: boolean;
readonly children: React.ReactNode;
readonly onClick: () => void;
-}> = ({checked, children, onClick}) => {
+}> = ({checked, disabled, children, onClick}) => {
return (
<button
aria-checked={checked}
+ disabled={disabled}
className={`${HOVERABLE_CLASS_NAME} ${FOCUS_VISIBLE_ONLY_CLASS_NAME}`}
onClick={onClick}
role="radio"
diff --git a/packages/studio/src/components/import-assets.ts b/packages/studio/src/components/import-assets.ts
index d6cf56d171..3161b33069 100644
--- a/packages/studio/src/components/import-assets.ts
+++ b/packages/studio/src/components/import-assets.ts
@@ -1327,6 +1327,7 @@ export const insertComposition = async ({
};
export const insertElement = async ({
+ installationName,
compositionFile,
compositionId,
element,
@@ -1335,6 +1336,7 @@ export const insertElement = async ({
from,
overwriteExisting,
}: {
+ installationName: string | null;
compositionFile: string;
compositionId: string;
element: InstallableElement;
@@ -1349,6 +1351,7 @@ export const insertElement = async ({
}
const response = await installElement({
+ installationName,
compositionFile,
compositionId,
element,
@@ -1364,7 +1367,7 @@ export const insertElement = async ({
? response.reason
: `Element file changed: ${response.conflict.filePath}`;
showNotification(`Could not add Element: ${reason}`, 4000);
- return;
+ return false;
}
requestInsertedElementSelection({
@@ -1372,6 +1375,7 @@ export const insertElement = async ({
nodePath: null,
notification: `Installed ${element.displayName}`,
});
+ return true;
} catch (error) {
showNotification(
`Could not add Element: ${
@@ -1379,5 +1383,6 @@ export const insertElement = async ({
}`,
4000,
);
+ return false;
}
};